Step 10: Building the User Interface

Building the User Interface

Everything is now in place to create the first version of the website user interface. We won’t make it pretty. Just functional for now.

Remember the escaping we had to do in the controller for the easter egg to avoid security issues? We won’t use PHP for our templates for that reason. Instead, we will use Twig. Besides handling output escaping for us, Twig brings a lot of nice features we will leverage, like template inheritance.

Installing Twig

We don’t need to add Twig as a dependency as it has already been installed as a transitive dependency of EasyAdmin. But what if you decide to switch to another admin bundle later on? One that uses an API and a React front-end for instance. It will probably not depend on Twig anymore, and so Twig will automatically be removed when you remove EasyAdmin.

For good measure, let’s tell Composer that the project really depends on Twig, independently of EasyAdmin. Adding it like any other dependency is enough:

  1. $ symfony composer req twig

Twig is now part of the main project dependencies in composer.json:

  1. --- a/composer.json
  2. +++ b/composer.json
  3. @@ -14,6 +14,7 @@
  4. "symfony/framework-bundle": "4.4.*",
  5. "symfony/maker-bundle": "^[email protected]",
  6. "symfony/orm-pack": "dev-master",
  7. + "symfony/twig-pack": "^1.0",
  8. "symfony/yaml": "4.4.*"
  9. },
  10. "require-dev": {

Using Twig for the Templates

All pages on the website will share the same layout. When installing Twig, a templates/ directory has been created automatically and a sample layout was created as well in base.html.twig.

templates/base.html.twig

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>{% block title %}Welcome!{% endblock %}</title>
  6. {% block stylesheets %}{% endblock %}
  7. </head>
  8. <body>
  9. {% block body %}{% endblock %}
  10. {% block javascripts %}{% endblock %}
  11. </body>
  12. </html>

A layout can define block elements, which are the places where child templates that extend the layout add their contents.

Let’s create a template for the project’s homepage in templates/conference/index.html.twig:

templates/conference/index.html.twig

  1. {% extends 'base.html.twig' %}
  2. {% block title %}Conference Guestbook{% endblock %}
  3. {% block body %}
  4. <h2>Give your feedback!</h2>
  5. {% for conference in conferences %}
  6. <h4>{{ conference }}</h4>
  7. {% endfor %}
  8. {% endblock %}

The template extends base.html.twig and redefines the title and body blocks.

The {% %} notation in a template indicates actions and structure.

The {{ }} notation is used to display something. {{ conference }} displays the conference representation (the result of calling __toString on the Conference object).

Using Twig in a Controller

Update the controller to render the Twig template:

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -2,22 +2,19 @@
  4. namespace App\Controller;
  5. +use App\Repository\ConferenceRepository;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. +use Twig\Environment;
  10. class ConferenceController extends AbstractController
  11. {
  12. #[Route('/', name: 'homepage')]
  13. - public function index(): Response
  14. + public function index(Environment $twig, ConferenceRepository $conferenceRepository): Response
  15. {
  16. - return new Response(<<<EOF
  17. -<html>
  18. - <body>
  19. - <img src="/images/under-construction.gif" />
  20. - </body>
  21. -</html>
  22. -EOF
  23. - );
  24. + return new Response($twig->render('conference/index.html.twig', [
  25. + 'conferences' => $conferenceRepository->findAll(),
  26. + ]));
  27. }
  28. }

There is a lot going on here.

To be able to render a template, we need the Twig Environment object (the main Twig entry point). Notice that we ask for the Twig instance by type-hinting it in the controller method. Symfony is smart enough to know how to inject the right object.

We also need the conference repository to get all conferences from the database.

In the controller code, the render() method renders the template and passes an array of variables to the template. We are passing the list of Conference objects as a conferences variable.

A controller is a standard PHP class. We don’t even need to extend the AbstractController class if we want to be explicit about our dependencies. You can remove it (but don’t do it, as we will use the nice shortcuts it provides in future steps).

Creating the Page for a Conference

Each conference should have a dedicated page to list its comments. Adding a new page is a matter of adding a controller, defining a route for it, and creating the related template.

Add a show() method in src/Controller/ConferenceController.php:

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -2,6 +2,8 @@
  4. namespace App\Controller;
  5. +use App\Entity\Conference;
  6. +use App\Repository\CommentRepository;
  7. use App\Repository\ConferenceRepository;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Response;
  10. @@ -17,4 +19,13 @@ class ConferenceController extends AbstractController
  11. 'conferences' => $conferenceRepository->findAll(),
  12. ]));
  13. }
  14. +
  15. + #[Route('/conference/{id}', name: 'conference')]
  16. + public function show(Environment $twig, Conference $conference, CommentRepository $commentRepository): Response
  17. + {
  18. + return new Response($twig->render('conference/show.html.twig', [
  19. + 'conference' => $conference,
  20. + 'comments' => $commentRepository->findBy(['conference' => $conference], ['createdAt' => 'DESC']),
  21. + ]));
  22. + }
  23. }

This method has a special behavior we have not seen yet. We ask for a Conference instance to be injected in the method. But there may be many of these in the database. Symfony is able to determine which one you want based on the {id} passed in the request path (id being the primary key of the conference table in the database).

Retrieving the comments related to the conference can be done via the findBy() method which takes a criteria as a first argument.

The last step is to create the templates/conference/show.html.twig file:

templates/conference/show.html.twig

  1. {% extends 'base.html.twig' %}
  2. {% block title %}Conference Guestbook - {{ conference }}{% endblock %}
  3. {% block body %}
  4. <h2>{{ conference }} Conference</h2>
  5. {% if comments|length > 0 %}
  6. {% for comment in comments %}
  7. {% if comment.photofilename %}
  8. <img src="{{ asset('uploads/photos/' ~ comment.photofilename) }}" />
  9. {% endif %}
  10. <h4>{{ comment.author }}</h4>
  11. <small>
  12. {{ comment.createdAt|format_datetime('medium', 'short') }}
  13. </small>
  14. <p>{{ comment.text }}</p>
  15. {% endfor %}
  16. {% else %}
  17. <div>No comments have been posted yet for this conference.</div>
  18. {% endif %}
  19. {% endblock %}

In this template, we are using the | notation to call Twig filters. A filter transforms a value. comments|length returns the number of comments and comment.createdAt|format_datetime('medium', 'short') formats the date in a human readable representation.

Try to reach the “first” conference via /conference/1, and notice the following error:

Step 10: Building the User Interface - 图1

The error comes from the format_datetime filter as it is not part of Twig core. The error message gives you a hint about which package should be installed to fix the problem:

  1. $ symfony composer req "twig/intl-extra:^3"

Now the page works properly.

Linking Pages Together

The very last step to finish our first version of the user interface is to link the conference pages from the homepage:

patch_file

  1. --- a/templates/conference/index.html.twig
  2. +++ b/templates/conference/index.html.twig
  3. @@ -7,5 +7,8 @@
  4. {% for conference in conferences %}
  5. <h4>{{ conference }}</h4>
  6. + <p>
  7. + <a href="/conference/{{ conference.id }}">View</a>
  8. + </p>
  9. {% endfor %}
  10. {% endblock %}

But hard-coding a path is a bad idea for several reasons. The most important reason is if you change the path (from /conference/{id} to /conferences/{id} for instance), all links must be updated manually.

Instead, use the path() Twig function and use the route name:

patch_file

  1. --- a/templates/conference/index.html.twig
  2. +++ b/templates/conference/index.html.twig
  3. @@ -8,7 +8,7 @@
  4. {% for conference in conferences %}
  5. <h4>{{ conference }}</h4>
  6. <p>
  7. - <a href="/conference/{{ conference.id }}">View</a>
  8. + <a href="{{ path('conference', { id: conference.id }) }}">View</a>
  9. </p>
  10. {% endfor %}
  11. {% endblock %}

The path() function generates the path to a page using its route name. The values of the route parameters are passed as a Twig map.

Paginating the Comments

With thousands of attendees, we can expect quite a few comments. If we display them all on a single page, it will grow very fast.

Create a getCommentPaginator() method in the Comment Repository that returns a Comment Paginator based on a conference and an offset (where to start):

patch_file

  1. --- a/src/Repository/CommentRepository.php
  2. +++ b/src/Repository/CommentRepository.php
  3. @@ -3,8 +3,10 @@
  4. namespace App\Repository;
  5. use App\Entity\Comment;
  6. +use App\Entity\Conference;
  7. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  8. use Doctrine\Persistence\ManagerRegistry;
  9. +use Doctrine\ORM\Tools\Pagination\Paginator;
  10. /**
  11. * @method Comment|null find($id, $lockMode = null, $lockVersion = null)
  12. @@ -14,11 +16,27 @@ use Doctrine\Persistence\ManagerRegistry;
  13. */
  14. class CommentRepository extends ServiceEntityRepository
  15. {
  16. + public const PAGINATOR_PER_PAGE = 2;
  17. +
  18. public function __construct(ManagerRegistry $registry)
  19. {
  20. parent::__construct($registry, Comment::class);
  21. }
  22. + public function getCommentPaginator(Conference $conference, int $offset): Paginator
  23. + {
  24. + $query = $this->createQueryBuilder('c')
  25. + ->andWhere('c.conference = :conference')
  26. + ->setParameter('conference', $conference)
  27. + ->orderBy('c.createdAt', 'DESC')
  28. + ->setMaxResults(self::PAGINATOR_PER_PAGE)
  29. + ->setFirstResult($offset)
  30. + ->getQuery()
  31. + ;
  32. +
  33. + return new Paginator($query);
  34. + }
  35. +
  36. // /**
  37. // * @return Comment[] Returns an array of Comment objects
  38. // */

We have set the maximum number of comments per page to 2 to ease testing.

To manage the pagination in the template, pass the Doctrine Paginator instead of the Doctrine Collection to Twig:

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -6,6 +6,7 @@ use App\Entity\Conference;
  4. use App\Repository\CommentRepository;
  5. use App\Repository\ConferenceRepository;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. +use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Twig\Environment;
  11. @@ -21,11 +22,16 @@ class ConferenceController extends AbstractController
  12. }
  13. #[Route('/conference/{id}', name: 'conference')]
  14. - public function show(Environment $twig, Conference $conference, CommentRepository $commentRepository): Response
  15. + public function show(Request $request, Environment $twig, Conference $conference, CommentRepository $commentRepository): Response
  16. {
  17. + $offset = max(0, $request->query->getInt('offset', 0));
  18. + $paginator = $commentRepository->getCommentPaginator($conference, $offset);
  19. +
  20. return new Response($twig->render('conference/show.html.twig', [
  21. 'conference' => $conference,
  22. - 'comments' => $commentRepository->findBy(['conference' => $conference], ['createdAt' => 'DESC']),
  23. + 'comments' => $paginator,
  24. + 'previous' => $offset - CommentRepository::PAGINATOR_PER_PAGE,
  25. + 'next' => min(count($paginator), $offset + CommentRepository::PAGINATOR_PER_PAGE),
  26. ]));
  27. }
  28. }

The controller gets the offset from the Request query string ($request->query) as an integer (getInt()), defaulting to 0 if not available.

The previous and next offsets are computed based on all the information we have from the paginator.

Finally, update the template to add links to the next and previous pages:

patch_file

  1. --- a/templates/conference/show.html.twig
  2. +++ b/templates/conference/show.html.twig
  3. @@ -6,6 +6,8 @@
  4. <h2>{{ conference }} Conference</h2>
  5. {% if comments|length > 0 %}
  6. + <div>There are {{ comments|length }} comments.</div>
  7. +
  8. {% for comment in comments %}
  9. {% if comment.photofilename %}
  10. <img src="{{ asset('uploads/photos/' ~ comment.photofilename) }}" />
  11. @@ -18,6 +20,13 @@
  12. <p>{{ comment.text }}</p>
  13. {% endfor %}
  14. +
  15. + {% if previous >= 0 %}
  16. + <a href="{{ path('conference', { id: conference.id, offset: previous }) }}">Previous</a>
  17. + {% endif %}
  18. + {% if next < comments|length %}
  19. + <a href="{{ path('conference', { id: conference.id, offset: next }) }}">Next</a>
  20. + {% endif %}
  21. {% else %}
  22. <div>No comments have been posted yet for this conference.</div>
  23. {% endif %}

You should now be able to navigate the comments via the “Previous” and “Next” links:

Step 10: Building the User Interface - 图2

Step 10: Building the User Interface - 图3

Refactoring the Controller

You might have noticed that both methods in ConferenceController take a Twig environment as an argument. Instead of injecting it into each method, let’s use some constructor injection instead (that makes the list of arguments shorter and less redundant):

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -13,21 +13,28 @@ use Twig\Environment;
  4. class ConferenceController extends AbstractController
  5. {
  6. + private $twig;
  7. +
  8. + public function __construct(Environment $twig)
  9. + {
  10. + $this->twig = $twig;
  11. + }
  12. +
  13. #[Route('/', name: 'homepage')]
  14. - public function index(Environment $twig, ConferenceRepository $conferenceRepository): Response
  15. + public function index(ConferenceRepository $conferenceRepository): Response
  16. {
  17. - return new Response($twig->render('conference/index.html.twig', [
  18. + return new Response($this->twig->render('conference/index.html.twig', [
  19. 'conferences' => $conferenceRepository->findAll(),
  20. ]));
  21. }
  22. #[Route('/conference/{id}', name: 'conference')]
  23. - public function show(Request $request, Environment $twig, Conference $conference, CommentRepository $commentRepository): Response
  24. + public function show(Request $request, Conference $conference, CommentRepository $commentRepository): Response
  25. {
  26. $offset = max(0, $request->query->getInt('offset', 0));
  27. $paginator = $commentRepository->getCommentPaginator($conference, $offset);
  28. - return new Response($twig->render('conference/show.html.twig', [
  29. + return new Response($this->twig->render('conference/show.html.twig', [
  30. 'conference' => $conference,
  31. 'comments' => $paginator,
  32. 'previous' => $offset - CommentRepository::PAGINATOR_PER_PAGE,

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.