Getting started with Symfony 4: View and Twig

March 3, 2019
Symfony View and Twig

As already discussed, learning Symfony is to learn installing and using powerful tools. I have introduced you to one of such tools, called Twig. In this article, I will cover more about twig and benefits of using such template engine. Unless you are building an API, twig will help you to deal with templates a lot easier.

Twig is a modern template engine for PHP

Twig defines three types of syntax:

{{  }} -> Which prints a variable or the result of an expression to the template.

{%  %} -> Used to execute statements, such as for-loops.

{#  #} -> It’s the equivalent of the PHP /* comment */.

Let’s test the syntax. First, create a directory called  blog  inside templates directory. Inside blog directory, create the file  index.html.twig . Using {% extends ‘base.html.twig’ %} you will extend the base.html.twig. You can use block body as before. To add something inside block body, just add {% block body %} {% endblock %}, and now you can add your html in between.

Twig allows you to write concise, readable templates that are more friendly to web designers and, in several ways, more powerful than PHP templates

Now, let’s assign some data to the view to be able to display the data in the template. Inside BlogController class, change method index as follows.

Instead of rendering base.html.twig, now we render blog/index.html.twig, and assigned data to the view. Edit index.html.twig inside blog directory, to display the data we assigned.

Here, you can see that using {{ }} you can say something or echo the variable. Using {% %} you can do something, extend templates, execute loops etc. There are a lot more built-in features that you can use.


Some of the most used ones are:

Browse the online reference to learn more about built-in features.

You Might Also Like


  • Reply Kévin March 7, 2019 at 10:20

    Can smarty be used with symfony 4?

    • Dejan Vujanović
      Reply dejanvujanovic March 7, 2019 at 22:50

      Smarty added support for Symfony 4 in October last year (2018). Take a look here.

    Leave a Reply