- 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:

- Boost C++ Application Development Cookbook(Second Edition)
- INSTANT Sencha Touch
- aelf區(qū)塊鏈應(yīng)用架構(gòu)指南
- Web全棧工程師的自我修養(yǎng)
- 秒懂設(shè)計(jì)模式
- Learning Network Forensics
- Learning ELK Stack
- Solr Cookbook(Third Edition)
- C#程序設(shè)計(jì)(項(xiàng)目教學(xué)版)
- Django 5企業(yè)級(jí)Web應(yīng)用開發(fā)實(shí)戰(zhàn)(視頻教學(xué)版)
- Mastering Concurrency Programming with Java 9(Second Edition)
- Mastering Apache Camel
- 零基礎(chǔ)學(xué)SQL(升級(jí)版)
- IBM RUP參考與認(rèn)證指南
- HTML并不簡(jiǎn)單:Web前端開發(fā)精進(jìn)秘籍