5. Javier Eguiluz
Formador + Programador
especializado en
nuevas tecnologías
Diseño y programación web
entusiasta del
framework Symfony
Comunidad sobre el framework Symfony
10. ¿Qué es Twig?
• Twig es un motor y lenguaje de
plantillas (como PHP, Smarty,
Moustache, etc.)
• Twig es el sistema de plantillas
utilizado por Drupal 8.
22. Variables de cada plantilla
{# core/modules/node/templates/node.html.twig #}
{# Default theme implementation to display a node.
Available variables:
- node: Full node entity.
- id: The node ID
- bundle: The type of the node, for example, "page" or "article".
- authorid: The user ID of the node author.
- createdtime: Formatted creation date.
... #}
<article id="node-{{ node.id }}" class="{{ attributes.class }} clearfix"{{ attributes }}>
{{ title_prefix }}
{% if not page %}
<h2{{ title_attributes }}>
<a href="{{ node_url }}" rel="bookmark">{{ label }}</a>
</h2>
{% endif %}
{{ title_suffix }}
{% if display_submitted %}
<footer>
{{ user_picture }}
las plantillas de
Drupal 8 listan
todas sus variables
37. Ejemplo de filtros para texto
lorEm iPsUm
{{ "..."|lower }}
{{ "..."|upper }}
{{ "..."|title }}
{{ "..."|capitalize }}
lorem ipsum
LOREM IPSUM
Lorem Ipsum
Lorem ipsum
38. Los filtros que define Twig
abs
batch
capitalize
convert_encoding
date
date_modify
default
escape
first
format
join
json_encode
keys
last
length
lower
merge
nl2br
number_format
raw
replace
reverse
slice
sort
split
striptags
title
trim
upper
url_encode
44. Aplicando filtros a varios elementos
<p>{{ nombre|striptags|trim }}</p>
<p>{{ apellidos|striptags|trim }}</p>
<p>{{ biografia|striptags|trim }}</p>
45. Aplicando filtros a varios elementos
{% filter striptags|trim %}
<p>{{ nombre }}</p>
<p>{{ apellidos }}</p>
<p>{{ biografia }}</p>
{% endfilter %}
50. Traduciendo contenidos variables
'More posts about Drupal 8'
'More posts about Twig'
'More posts about Symfony'
traducir la
parte fija
considerarlo
una variable
63. La etiqueta IF básica
{# core/modules/block/templates/block.html.twig #}
<div>
{{ title_prefix }}
{% if label %}
<h2 {{ attributes }}>{{ label }}</h2>
{% endif %}
{{ title_suffix }}
</div>
64. La etiqueta IF básica
{# core/modules/block/templates/block.html.twig #}
<div>
✔ Existe la variable
{{ title_prefix }}
✔ No es null
{% if label %}
✔ No es cadena vacía
<h2 {{ attributes }}>{{ label }}</h2>
{% endif %}
{{ title_suffix }}
</div>
72. Condiciones múltiples
{% if not label_hidden %}
{% if not label_hidden or user.is_admin %}
{% if label_hidden and not user.is_admin %}
{% if (label_hidden or user.is_admin)
and node.is_published %}
77. ERROR
An exception has been thrown
during the rendering of a template:
"Catchable Fatal Error: Object of
class DateTime could not be
converted to string in [...] line XX"
93. Las migas de pan del foro
{# core/modules/forum/lib/Drupal/forum/ForumBreadcrumbBuilder.php #}
function forumPostBreadcrumb($node) {
$vocabulary = $this->entityManager->...->load('...');
$breadcrumb[] = l(t('Home'), NULL);
$breadcrumb[] = l($vocabulary->label(), 'forum');
// ...
return $breadcrumb;
}
94. Mostrando las migas de pan
<nav class="breadcrumb" role="navigation">
<ol>
{% for item in breadcrumb %}
<li>{{ item }}</li>
{% endfor %}
</ol>
</nav>
95. Mostrando las migas de pan
<nav class="breadcrumb" role="navigation">
<ol>
{% for item in breadcrumb %}
<li>{{ item }}</li>
{% endfor %}
</ol>
</nav>
96. Mostrando las migas de pan
<nav class="breadcrumb" role="navigation">
<ol>
{% for item in breadcrumb %}
<li>{{ item }}</li>
{% endfor %}
</ol>
</nav>
106. ¿Y si no hay libros?
{% for book_id, menu in book_menus %}
<nav id="book-block-menu-{{ book_id }}">
{{ menu }}
</nav>
{% else %}
<p>No se ha publicado todavía ningún libro.</p>
{% endfor %}
107. El bucle FOR
{% for valor in coleccion %}
...
{% else %}
...
{% endfor %}
108. Indentando los mensajes del foro
<div class="indent">
<div class="indent">
<div class="indent">
<div class="indent">
forum.depth
Lorem ipsum dolor sit amet, consectetur adipisic
ingelit, sed do eiusmodtempor incididunt ut labore
et dolore magna aliqua.
</div>
</div>
</div>
</div>
109. Indentando los mensajes del foro
<div class="indent">
<div class="indent">
<div class="indent">
<div class="indent">
sólo si depth es
mayor que cero
forum.depth
Lorem ipsum dolor sit amet, consectetur adipisic
ingelit, sed do eiusmodtempor incididunt ut labore
et dolore magna aliqua.
</div>
</div>
</div>
</div>
110. Indentando los mensajes del foro
{% for i in 1..forum.depth if forum.depth > 0 %}
<div class="indent">
{% endfor %}
111. El bucle FOR
{% for valor in coleccion if condicion %}
...
{% endfor %}
112. El bucle FOR completo
{% for clave, valor in coleccion
if condicion %}
...
{% else %}
...
{% endfor %}
113. Los filtros para colecciones
{% for ... in coleccion|sort %}
{% for ... in coleccion|reverse %}
{% for ... in coleccion|merge(otra_coleccion) %}
{% for ... in coleccion|slice(1, 3) %}
120. Twig escapa todo por defecto
<strong>Lorem ipsum</strong>
dolor sit <em>amet</em>
{{ descripcion }}
<strong>Lorem ipsum</
strong> dolor sit
<em>amet</em>
121. La gran diferencia entre Twig y PHP
<h1>{{ titulo }}</h1>
<h1><?php echo $titulo; ?></h1>
TWIG
PHP
SEGURO
INSEGURO
POR DEFECTO
POR DEFECTO
122. El filtro raw
{{ descripcion|raw }}
<strong>Lorem ipsum</strong>
dolor sit <em>amet</em>
123. El filtro escape
{{ descripcion|e }}
<strong>Lorem ipsum</
strong> dolor sit
<em>amet</em>
124. Diferentes estrategias de escape
{{ descripcion|e('html') }}
<strong>Lorem ipsum</strong> dolor sit
<em>amet</em>
{{ descripcion|e('js') }}
x3Cstrongx3ELoremx20ipsumx3Cx2Fstrongx3E
x20dolorx20sitx20x3Cemx3Eametx3Cx2Fem
x3E
128. Utilizando bucles normales
<table>
{% for i in 1..9 %}
{% if 0 == i % 3 %}<tr>{% endif %}
<td>{{ i }}</td>
{% if 0 == i % 3 %}</tr>{% endif %}
{% endfor %}
</table>
129. El filtro batch
<table>
{% for fila in 1..9|batch(3) %}
<tr>
{% for columna in fila %}
<td> {{ columna }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
130. El filtro batch
<table>
saca los elementos
de tres en tres
{% for fila in 1..9|batch(3) %}
<tr>
{% for columna in fila %}
<td> {{ columna }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
131. Rellenando los huecos
<table>
{% for fila in 1..7|batch(3, '-') %}
<tr>
{% for columna in fila %}
<td> {{ columna }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
132. Rellenando los huecos
<table>
{% for fila in 1..7|batch(3, '-') %}
<tr>
{% for columna in fila %}
<td> {{ columna }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
1
2
3
4
5
6
7
-
-
140. Mejorando la depuración
• dump( ) es muy útil, pero no deja de
ser un simple var_dump( ).
• Resulta muy difícil depurar variables
complejas.
• Drupal 8 podría integrar el proyecto
LadyBug.
161. Cómo funciona la herencia en Twig
• Cada plantilla puede definir tantos
bloques como quiera.
• La herencia permite, pero no obliga,
a rellenar los huecos.
• La plantilla padre puede rellenar sus
huecos con contenido por defecto.
171. plantilla padre
plantilla hija
A
C
B
<div>{% block uno %}
A
{% endblock %}</div>
<div>{% block dos %}
B
{% endblock %}</div>
D
{% extends 'padre.twig' %}
{% block uno %}
C
{% endblock %}
{% block dos %}
D
{% endblock %}
173. plantilla padre
plantilla hija
A
A
B
<div>{% block uno %}
A
{% endblock %}</div>
<div>{% block dos %}
B
{% endblock %}</div>
D
{% extends 'padre.twig' %}
{% block dos %}
D
{% endblock %}
175. plantilla padre
plantilla hija
A
A
C
B
<div>{% block uno %}
A
{% endblock %}</div>
<div>{% block dos %}
B
{% endblock %}</div>
D
{% extends 'padre.twig' %}
{% block uno %}
{{ parent() }}
C
{% endblock %}
{% block dos %}
D
{% endblock %}
176. plantilla padre
plantilla hija
A
A
C
B
<div>{% block uno %}
A
{% endblock %}</div>
<div>{% block dos %}
B
{% endblock %}</div>
D
{% extends 'padre.twig' %}
{% block uno %}
{{ parent() }}
C
{% endblock %}
{% block dos %}
D
{% endblock %}
199. Conclusiones
• Twig mejora tu productividad y hace
que tus plantillas sean seguras.
• Drupal 8 utiliza actualmente el 10%
de las posibilidades de Twig.
200. Conclusiones
• Twig mejora tu productividad y hace
que tus plantillas sean seguras.
• Drupal 8 utiliza actualmente el 10%
de las posibilidades de Twig.
• Twig es la parte más sencilla y
divertida de la symfonización de
Drupal.