1
1
The View
2
2
========
3
3
4
- After 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 `Twig `_, the Symfony2 template engine. 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.
4
+ In this second chapter, you will learn more about `Twig `_, the fast, flexible,
5
+ and secure template engine for PHP. Twig makes your templates more readable and
6
+ concise; it also makes them more friendly for web designers.
9
7
10
8
Getting familiar with Twig
11
9
--------------------------
12
10
13
- The official Twig ` documentation `_ is the best resource to learn everything
14
- abut this new template engine. This section just gives you a quick overview of
11
+ The official ` Twig documentation `_ is the best resource to learn everything
12
+ about this new template engine. This section just gives you a quick overview of
15
13
its main concepts.
16
14
17
15
A Twig template is a text file that can generate any type of content (HTML, CSS,
18
- JavaScript, XML, CSV, LaTeX, ...). Twig defines three kinds of delimiters:
16
+ JavaScript, XML, CSV, LaTeX, ...). Twig elements are separated from the rest of
17
+ the template contents using any of these delimiters:
19
18
20
19
* ``{{ ... }} ``: prints the content of a variable or the result of an expression;
21
20
22
- * ``{% ... %} ``: controls the logic of the template; it is used to execute
23
- ``for `` loops and ``if `` statements, for example ;
21
+ * ``{% ... %} ``: controls the logic of the template; it is used for example to
22
+ execute ``for `` loops and ``if `` statements;
24
23
25
24
* ``{# ... #} ``: allows to include comments inside templates.
26
25
@@ -32,52 +31,54 @@ Below is a minimal template that illustrates a few basics, using two variables
32
31
<!DOCTYPE html>
33
32
<html>
34
33
<head>
35
- <title>My Webpage </title>
34
+ <title>{{ page_title }} </title>
36
35
</head>
37
36
<body>
38
37
<h1>{{ page_title }}</h1>
39
38
40
39
<ul id="navigation">
41
40
{% for item in navigation %}
42
- <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
41
+ <li><a href="{{ item.url }}">{{ item.label }}</a></li>
43
42
{% endfor %}
44
43
</ul>
45
44
</body>
46
45
</html>
47
46
48
47
To render a template in Symfony, use the ``render `` method from within a controller
49
- and pass it any variables needed in the template ::
48
+ and pass the variables needed as an array using the optional second argument ::
50
49
51
50
$this->render('AcmeDemoBundle:Demo:hello.html.twig', array(
52
51
'name' => $name,
53
52
));
54
53
55
54
Variables passed to a template can be strings, arrays, or even objects. Twig
56
55
abstracts the difference between them and lets you access "attributes" of a
57
- variable with the dot (``. ``) notation:
56
+ variable with the dot (``. ``) notation. The following code listing shows how to
57
+ display the content of a variable depending on the type of variable passed by
58
+ the controller:
58
59
59
60
.. code-block :: jinja
60
61
62
+ {# 1. Simple variables #}
61
63
{# array('name' => 'Fabien') #}
62
64
{{ name }}
63
65
66
+ {# 2. Arrays #}
64
67
{# array('user' => array('name' => 'Fabien')) #}
65
68
{{ user.name }}
66
69
67
- {# force array lookup #}
70
+ {# alternative syntax for arrays #}
68
71
{{ user['name'] }}
69
72
73
+ {# 3. Objects #}
70
74
{# array('user' => new User('Fabien')) #}
71
75
{{ user.name }}
72
76
{{ user.getName }}
73
77
74
- {# force method name lookup #}
78
+ {# alternative syntax for objects #}
75
79
{{ user.name() }}
76
80
{{ user.getName() }}
77
81
78
- {# pass arguments to a method #}
79
- {{ user.date('Y-m-d') }}
80
-
81
82
Decorating Templates
82
83
--------------------
83
84
@@ -116,28 +117,38 @@ Now, simplify the ``layout.html.twig`` template:
116
117
{% endblock %}
117
118
</div>
118
119
119
- The ``{% block %} `` tags define blocks that child templates can fill in. All
120
- the ``{% block %} `` tag does is to tell the template engine that a child
121
- template may override those portions of the template.
122
-
123
- In this example, the ``hello.html.twig `` template overrides the ``content ``
124
- block, meaning that the "Hello Fabien" text is rendered inside the ``<div> ``
125
- element.
120
+ The ``{% block %} `` tags tell the template engine that a child template may
121
+ override those portions of the template. In this example, the ``hello.html.twig ``
122
+ template overrides the ``content `` block, meaning that the "Hello Fabien" text
123
+ is rendered inside the ``<div> `` element.
126
124
127
125
Using Tags, Filters, and Functions
128
126
----------------------------------
129
127
130
128
One of the best feature of Twig is its extensibility via tags, filters, and
131
- functions. Symfony2 comes bundled with many of these built-in to ease the
132
- work of the template designer.
129
+ functions. Take a look at the following sample template that uses filters
130
+ extensively to modify the information before displaying it to the user:
131
+
132
+ .. code-block :: jinja
133
+
134
+ <h1>{{ article.title|trim|capitalize }}</h1>
135
+
136
+ <p>{{ article.content|striptags|slice(0, 1024) }}</p>
137
+
138
+ <p>Tags: {{ article.tags|sort|join(", ") }}</p>
139
+
140
+ <p>Next article will be published on {{ 'next Monday'|date('M j, Y')}}</p>
141
+
142
+ Don't forget to check out the official `Twig documentation `_ to learn everything
143
+ about filters, functions and tags.
133
144
134
145
Including other Templates
135
146
~~~~~~~~~~~~~~~~~~~~~~~~~
136
147
137
- The best way to share a snippet of code between several distinct templates is
138
- to create a new template that can then be included from other templates.
148
+ The best way to share a snippet of code between several templates is to create a
149
+ new template fragment that can then be included from other templates.
139
150
140
- Create an ``embedded.html.twig `` template:
151
+ First, create an ``embedded.html.twig `` template:
141
152
142
153
.. code-block :: jinja
143
154
@@ -163,32 +174,31 @@ And what if you want to embed the result of another controller in a template?
163
174
That's very useful when working with Ajax, or when the embedded template needs
164
175
some variable not available in the main template.
165
176
166
- Suppose you've created a ``fancyAction `` controller method, and you want to
167
- "render" it inside the ``index `` template, which means including the result
168
- (e.g. ``HTML ``) of the controller. To do this, use the ``render `` function:
177
+ Suppose you've created a ``topArticlesAction `` controller method to display the
178
+ most popular articles of your website. If you want to "render" the result of
179
+ that method (e.g. ``HTML ``) inside the ``index `` template, use the ``render ``
180
+ function:
169
181
170
182
.. code-block :: jinja
171
183
172
184
{# src/Acme/DemoBundle/Resources/views/Demo/index.html.twig #}
173
- {{ render(controller("AcmeDemoBundle:Demo:fancy ", {'name ': name, 'color': 'green' })) }}
185
+ {{ render(controller("AcmeDemoBundle:Demo:topArticles ", {'num ': 10 })) }}
174
186
175
- Here, the ``AcmeDemoBundle:Demo:fancy `` string refers to the ``fancy `` action
176
- of the ``Demo `` controller. The arguments (``name `` and ``color ``) act like
177
- simulated request variables (as if the ``fancyAction `` were handling a whole
178
- new request) and are made available to the controller::
187
+ Here, the ``AcmeDemoBundle:Demo:topArticles `` string refers to the
188
+ ``topArticlesAction `` action of the ``Demo `` controller, and the ``num ``
189
+ argument is made available to the controller::
179
190
180
191
// src/Acme/DemoBundle/Controller/DemoController.php
181
192
182
193
class DemoController extends Controller
183
194
{
184
- public function fancyAction($name, $color )
195
+ public function topArticlesAction($num )
185
196
{
186
- // create some object, based on the $color variable
187
- $object = ...;
197
+ // look for the $num most popular articles in the database
198
+ $articles = ...;
188
199
189
- return $this->render('AcmeDemoBundle:Demo:fancy.html.twig', array(
190
- 'name' => $name,
191
- 'object' => $object,
200
+ return $this->render('AcmeDemoBundle:Demo:topArticles.html.twig', array(
201
+ 'articles' => $articles,
192
202
));
193
203
}
194
204
@@ -208,9 +218,8 @@ updated by just changing the configuration:
208
218
<a href="{{ path('_demo_hello', { 'name': 'Thomas' }) }}">Greet Thomas!</a>
209
219
210
220
The ``path `` function takes the route name and an array of parameters as
211
- arguments. The route name is the main key under which routes are referenced
212
- and the parameters are the values of the variables defined in the route
213
- pattern::
221
+ arguments. The route name is the key under which routes are defined and the
222
+ parameters are the values of the variables defined in the route pattern::
214
223
215
224
// src/Acme/DemoBundle/Controller/DemoController.php
216
225
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
@@ -267,5 +276,5 @@ But I'm getting ahead of myself. First, you need to learn more about the control
267
276
and that's exactly the topic of the :doc: `next part of this tutorial <the_controller >`.
268
277
Ready for another 10 minutes with Symfony2?
269
278
270
- .. _Twig : http://twig.sensiolabs.org/
271
- .. _ documentation : http://twig.sensiolabs.org/documentation
279
+ .. _Twig : http://twig.sensiolabs.org/
280
+ .. _ Twig documentation : http://twig.sensiolabs.org/documentation
0 commit comments