- Mastering Symfony
- Sohail Salehi
- 212字
- 2021-07-16 11:28:59
Dynamic templates and controllers
Now that we have a few records in our table, let's see how to fetch them via controller and feed their properties to our templates. What we expect from our dynamic template is to receive an object and show its properties. In our case, the object is User
and its properties are name
, bio
, and email
. So, edit the about/index.html.twig
template as follows:
{# mava/app/Resources/views/about/index.html.twig #} {% if user %} <h1>User Profile</h1> <strong>Name: </strong>{{user.name}} <br/> <strong>email: </strong>{{user.email}} <br/> <strong>Bio: </strong>{{user.bio}} <br/> {% else %} mava is a web app for task management and team collaboration. <br/> {% endif %}
Next, add a few lines to aboutAction()
to retrieve information about the given user:
<?php // AppBundle/Controller/DefaultController.php // … use AppBundle\Entity\User; // ... /** * @Route("/about/{name}", name="aboutpage", defaults={"name":null}) */ public function aboutAction($name) { if ($name) { $user = $this->getDoctrine() ->getRepository('AppBundle:User') ->findOneBy(array('name'=>$name)); if (false === $user instanceof User) { throw $this->createNotFoundException( 'No user named '.$name.' found!' ); } } return $this->render('about/index.html.twig', array('user' => $user)); }
This action first accesses the Doctrine service, and, via this, approaches the User
entity. The next step would be to find the first record that has a john
value for its name
property.
If no record is found, an exception will be thrown; otherwise, the found object will be passed to the index.html.twig
template.
That's it. If you visit the http://localhost:8000/about/john
or http://localhost:8000/about/jack
URL, you will see that it works as we expected:

- 少兒人工智能趣味入門:Scratch 3.0動(dòng)畫與游戲編程
- Clojure Programming Cookbook
- Oracle 11g從入門到精通(第2版) (軟件開發(fā)視頻大講堂)
- INSTANT OpenCV Starter
- 動(dòng)手玩轉(zhuǎn)Scratch3.0編程:人工智能科創(chuàng)教育指南
- Java技術(shù)手冊(cè)(原書第7版)
- Instant Typeahead.js
- AutoCAD VBA參數(shù)化繪圖程序開發(fā)與實(shí)戰(zhàn)編碼
- 名師講壇:Spring實(shí)戰(zhàn)開發(fā)(Redis+SpringDataJPA+SpringMVC+SpringSecurity)
- Building an RPG with Unity 2018
- 組態(tài)軟件技術(shù)與應(yīng)用
- 輕松上手2D游戲開發(fā):Unity入門
- Kubernetes源碼剖析
- Learning Kotlin by building Android Applications
- Access數(shù)據(jù)庫應(yīng)用教程(2010版)