@@ -2,32 +2,28 @@ The View
22========
33
44After reading the first part of this tutorial, you have decided that Symfony2
5- was worth another 10 minutes. Great choice! In this second part, you will
6- learn more about the Symfony2 template engine, `Twig `_. Twig is a flexible,
7- fast, and secure template engine for PHP. It makes your templates more
8- readable and concise; it also makes them more friendly for web designers.
9-
10- .. note ::
11-
12- Instead of Twig, you can also use :doc: `PHP </cookbook/templating/PHP >`
13- for your templates. Both template engines are supported by Symfony2.
5+ was worth another 10 minutes. In this second part, you will learn more about
6+ `Twig `_, the fast, flexible, and secure template engine for PHP. Twig makes your
7+ templates more readable and concise; it also makes them more friendly for web
8+ designers.
149
1510Getting familiar with Twig
1611--------------------------
1712
18- .. tip ::
13+ The official `Twig documentation `_ is the best resource to learn everything
14+ about this new template engine. This section just gives you a quick overview of
15+ its main concepts.
1916
20- If you want to learn Twig, it's highly recommended you read its official
21- ` documentation `_. This section is just a quick overview of the main
22- concepts.
17+ A Twig template is a text file that can generate any type of content (HTML, CSS,
18+ JavaScript, XML, CSV, LaTeX, ...). Twig elements are separated from the rest of
19+ the template contents using any of these delimiters:
2320
24- A Twig template is a text file that can generate any type of content (HTML,
25- XML, CSV, LaTeX, ...). Twig defines two kinds of delimiters:
21+ * ``{{ ... }} ``: prints the content of a variable or the result of an expression;
2622
27- * ``{{ ... }} ``: Prints a variable or the result of an expression;
23+ * ``{% ... %} ``: controls the logic of the template; it is used for example to
24+ execute ``for `` loops and ``if `` statements;
2825
29- * ``{% ... %} ``: Controls the logic of the template; it is used to execute
30- ``for `` loops and ``if `` statements, for example.
26+ * ``{# ... #} ``: allows including comments inside templates.
3127
3228Below is a minimal template that illustrates a few basics, using two variables
3329``page_title `` and ``navigation ``, which would be passed into the template:
@@ -37,74 +33,65 @@ Below is a minimal template that illustrates a few basics, using two variables
3733 <!DOCTYPE html>
3834 <html>
3935 <head>
40- <title>My Webpage </title>
36+ <title>{{ page_title }} </title>
4137 </head>
4238 <body>
4339 <h1>{{ page_title }}</h1>
4440
4541 <ul id="navigation">
4642 {% for item in navigation %}
47- <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
43+ <li><a href="{{ item.url }}">{{ item.label }}</a></li>
4844 {% endfor %}
4945 </ul>
5046 </body>
5147 </html>
5248
53- .. tip ::
54-
55- Comments can be included inside templates using the ``{# ... #} `` delimiter.
56-
5749To render a template in Symfony, use the ``render `` method from within a controller
58- and pass it any variables needed in the template ::
50+ and pass the variables needed as an array using the optional second argument ::
5951
6052 $this->render('AcmeDemoBundle:Demo:hello.html.twig', array(
6153 'name' => $name,
6254 ));
6355
6456Variables passed to a template can be strings, arrays, or even objects. Twig
6557abstracts the difference between them and lets you access "attributes" of a
66- variable with the dot (``. ``) notation:
58+ variable with the dot (``. ``) notation. The following code listing shows how to
59+ display the content of a variable depending on the type of the variable passed
60+ by the controller:
6761
6862.. code-block :: jinja
6963
64+ {# 1. Simple variables #}
7065 {# array('name' => 'Fabien') #}
7166 {{ name }}
7267
68+ {# 2. Arrays #}
7369 {# array('user' => array('name' => 'Fabien')) #}
7470 {{ user.name }}
7571
76- {# force array lookup #}
72+ {# alternative syntax for arrays #}
7773 {{ user['name'] }}
7874
75+ {# 3. Objects #}
7976 {# array('user' => new User('Fabien')) #}
8077 {{ user.name }}
8178 {{ user.getName }}
8279
83- {# force method name lookup #}
80+ {# alternative syntax for objects #}
8481 {{ user.name() }}
8582 {{ user.getName() }}
8683
87- {# pass arguments to a method #}
88- {{ user.date('Y-m-d') }}
89-
90- .. note ::
91-
92- It's important to know that the curly braces are not part of the variable
93- but the print statement. If you access variables inside tags don't put the
94- braces around.
95-
9684 Decorating Templates
9785--------------------
9886
9987More often than not, templates in a project share common elements, like the
100- well-known header and footer. In Symfony2, you think about this problem
101- differently: a template can be decorated by another one. This works exactly
102- the same as PHP classes: template inheritance allows you to build a base
103- "layout" template that contains all the common elements of your site and
104- defines "blocks" that child templates can override.
88+ well-known header and footer. Twig solves this problem elegantly with a concept
89+ called "template inheritance". This feature allows you to build a base "layout"
90+ template that contains all the common elements of your site and defines "blocks"
91+ that child templates can override.
10592
106- The ``hello.html.twig `` template inherits from ``layout.html.twig ``, thanks to
107- the `` extends `` tag :
93+ The ``hello.html.twig `` template uses the ``extends `` tag to indicate that it
94+ inherits from the common `` layout.html.twig `` template :
10895
10996.. code-block :: html+jinja
11097
@@ -120,40 +107,50 @@ the ``extends`` tag:
120107The ``AcmeDemoBundle::layout.html.twig `` notation sounds familiar, doesn't it?
121108It is the same notation used to reference a regular template. The ``:: `` part
122109simply means that the controller element is empty, so the corresponding file
123- is directly stored under the ``Resources/views/ `` directory.
110+ is directly stored under the ``Resources/views/ `` directory of the bundle .
124111
125112Now, simplify the ``layout.html.twig `` template:
126113
127114.. code-block :: jinja
128115
129116 {# src/Acme/DemoBundle/Resources/views/layout.html.twig #}
130- <div class="symfony-content" >
117+ <div>
131118 {% block content %}
132119 {% endblock %}
133120 </div>
134121
135- The ``{% block %} `` tags define blocks that child templates can fill in. All
136- the block tag does is to tell the template engine that a child template may
137- override those portions of the template.
138-
139- In this example, the ``hello.html.twig `` template overrides the ``content ``
140- block, meaning that the "Hello Fabien" text is rendered inside the ``div.symfony-content ``
141- element.
122+ The ``{% block %} `` tags tell the template engine that a child template may
123+ override those portions of the template. In this example, the ``hello.html.twig ``
124+ template overrides the ``content `` block, meaning that the "Hello Fabien" text
125+ is rendered inside the ``<div> `` element.
142126
143127Using Tags, Filters, and Functions
144128----------------------------------
145129
146130One of the best feature of Twig is its extensibility via tags, filters, and
147- functions. Symfony2 comes bundled with many of these built-in to ease the
148- work of the template designer.
131+ functions. Take a look at the following sample template that uses filters
132+ extensively to modify the information before displaying it to the user:
133+
134+ .. code-block :: jinja
135+
136+ <h1>{{ article.title|trim|capitalize }}</h1>
137+
138+ <p>{{ article.content|striptags|slice(0, 1024) }}</p>
139+
140+ <p>Tags: {{ article.tags|sort|join(", ") }}</p>
141+
142+ <p>Next article will be published on {{ 'next Monday'|date('M j, Y')}}</p>
143+
144+ Don't forget to check out the official `Twig documentation `_ to learn everything
145+ about filters, functions and tags.
149146
150147Including other Templates
151148~~~~~~~~~~~~~~~~~~~~~~~~~
152149
153- The best way to share a snippet of code between several distinct templates is
154- to create a new template that can then be included from other templates.
150+ The best way to share a snippet of code between several templates is to create a
151+ new template fragment that can then be included from other templates.
155152
156- Create an ``embedded.html.twig `` template:
153+ First, create an ``embedded.html.twig `` template:
157154
158155.. code-block :: jinja
159156
@@ -179,32 +176,31 @@ And what if you want to embed the result of another controller in a template?
179176That's very useful when working with Ajax, or when the embedded template needs
180177some variable not available in the main template.
181178
182- Suppose you've created a ``fancyAction `` controller method, and you want to
183- "render" it inside the ``index `` template, which means including the result
184- (e.g. ``HTML ``) of the controller. To do this, use the ``render `` function:
179+ Suppose you've created a ``topArticlesAction `` controller method to display the
180+ most popular articles of your website. If you want to "render" the result of
181+ that method (e.g. ``HTML ``) inside the ``index `` template, use the ``render ``
182+ function:
185183
186184.. code-block :: jinja
187185
188186 {# src/Acme/DemoBundle/Resources/views/Demo/index.html.twig #}
189- {{ render(controller("AcmeDemoBundle:Demo:fancy ", {'name ': name, 'color': 'green' })) }}
187+ {{ render(controller("AcmeDemoBundle:Demo:topArticles ", {'num ': 10 })) }}
190188
191- Here, the ``AcmeDemoBundle:Demo:fancy `` string refers to the ``fancy `` action
192- of the ``Demo `` controller. The arguments (``name `` and ``color ``) act like
193- simulated request variables (as if the ``fancyAction `` were handling a whole
194- new request) and are made available to the controller::
189+ Here, the ``AcmeDemoBundle:Demo:topArticles `` string refers to the
190+ ``topArticlesAction `` action of the ``Demo `` controller, and the ``num ``
191+ argument is made available to the controller::
195192
196193 // src/Acme/DemoBundle/Controller/DemoController.php
197194
198195 class DemoController extends Controller
199196 {
200- public function fancyAction($name, $color )
197+ public function topArticlesAction($num )
201198 {
202- // create some object, based on the $color variable
203- $object = ...;
199+ // look for the $num most popular articles in the database
200+ $articles = ...;
204201
205- return $this->render('AcmeDemoBundle:Demo:fancy.html.twig', array(
206- 'name' => $name,
207- 'object' => $object,
202+ return $this->render('AcmeDemoBundle:Demo:topArticles.html.twig', array(
203+ 'articles' => $articles,
208204 ));
209205 }
210206
@@ -214,8 +210,8 @@ new request) and are made available to the controller::
214210Creating Links between Pages
215211~~~~~~~~~~~~~~~~~~~~~~~~~~~~
216212
217- Speaking of web applications, creating links between pages is a must. Instead
218- of hardcoding URLs in templates, the ``path `` function knows how to generate
213+ Creating links between pages is a must for web applications . Instead of
214+ hardcoding URLs in templates, the ``path `` function knows how to generate
219215URLs based on the routing configuration. That way, all your URLs can be easily
220216updated by just changing the configuration:
221217
@@ -224,9 +220,8 @@ updated by just changing the configuration:
224220 <a href="{{ path('_demo_hello', { 'name': 'Thomas' }) }}">Greet Thomas!</a>
225221
226222The ``path `` function takes the route name and an array of parameters as
227- arguments. The route name is the main key under which routes are referenced
228- and the parameters are the values of the placeholders defined in the route
229- pattern::
223+ arguments. The route name is the key under which routes are defined and the
224+ parameters are the values of the variables defined in the route pattern::
230225
231226 // src/Acme/DemoBundle/Controller/DemoController.php
232227 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
@@ -245,8 +240,9 @@ pattern::
245240
246241.. tip ::
247242
248- The ``url `` function generates *absolute * URLs: ``{{ url('_demo_hello', {
249- 'name': 'Thomas'}) }} ``.
243+ The ``url `` function is very similar to the ``path `` function, but generates
244+ *absolute * URLs, which is very handy when rendering emails and RSS files:
245+ ``{{ url('_demo_hello', {'name': 'Thomas'}) }} ``.
250246
251247Including Assets: images, JavaScripts, and stylesheets
252248~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -265,13 +261,6 @@ Thanks to this function, you can move the application root directory anywhere
265261under your web root directory without changing anything in your template's
266262code.
267263
268- Escaping Variables
269- ------------------
270-
271- Twig is configured to automatically escape all output by default. Read Twig
272- `documentation `_ to learn more about output escaping and the Escaper
273- extension.
274-
275264Final Thoughts
276265--------------
277266
@@ -289,5 +278,5 @@ But I'm getting ahead of myself. First, you need to learn more about the control
289278and that's exactly the topic of the :doc: `next part of this tutorial <the_controller >`.
290279Ready for another 10 minutes with Symfony2?
291280
292- .. _Twig : http://twig.sensiolabs.org/
293- .. _ documentation : http://twig.sensiolabs.org/documentation
281+ .. _Twig : http://twig.sensiolabs.org/
282+ .. _ Twig documentation : http://twig.sensiolabs.org/documentation
0 commit comments