官术网_书友最值得收藏!

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:

Dynamic templates and controllers
主站蜘蛛池模板: 崇左市| 海安县| 施甸县| 布拖县| 天峻县| 青冈县| 武冈市| 沈丘县| 怀化市| 保德县| 沁源县| 古交市| 五莲县| 肥西县| 溆浦县| 绥滨县| 密山市| 和平区| 浪卡子县| 舟曲县| 大足县| 桐庐县| 贵南县| 万盛区| 乌拉特中旗| 靖江市| 库伦旗| 沈丘县| 房产| 绵阳市| 新泰市| 新建县| 阿克苏市| 黄平县| 威海市| 阳城县| 宁乡县| 吉林省| 嘉禾县| 双桥区| 宜兰市|