D8 Twig - pierregermain/MyDrupal GitHub Wiki
https://github.com/pierregermain/MyDrupal/wiki/D8-Twig:-Obtener-datos-de-fields
- Variable simple
{{ title }}
- Variable con atributos (Objeto PHP)
{{ foo.bar }}
- Variable con elementos (Array PHP)
{{ foo['bar'] }}
- Variable con chars especiales:
{{ attribute(foo, 'data-bar') }}
equivalente a{{ foo.data-bar }}
{% if foo %}
<div>{{ foo }}</div>
{% endif %}
{% set foo = 'bar' %}
{% set foo = [1, 2] %}
{% set accordion_color = [
content.field_accordion_color[0]['#markup']
] %}
{% set accordion_style = [
content.field_accordion_style[0]['#markup']
] %}
Asignar hash
{% set myHash = random() %}
Usar asignaciones
<div class="accordion-component accordion
accordion-style-{{ accordion_style.0 }}"
id="accordionComponent{{ myHash }}"
style="--custom_color: {{ accordion_color.0 }}">
{% set fullwidth = [
content.field_fullwidth[0]['#markup']
] %}
<div{{ attributes }}>
{{ title_suffix.contextual_links }}
{% if fullwidth[0] %}
<div class="video-wrapper fullwidth">
{{ content.field_media_video_file }}
</div>
{% else %}
{{ content.field_media_video_file }}
{% endif %}
</div>
{{ _self }}
{{ _context }}
{{ _charset }}
{{ foo|upper }}
{% filter upper %}
Este texto se convertirá a mayúsculas
{% endfilter %}
{{ 'WELCOME'|lower }}
{{ 'welcome home'|capitalize }}
{# Resultado: Welcome home #}
{{ 'welcome home'|title }}
{# Resultado: Welcome Home #}
{{ "now"|date("d/m/Y") }}
{{ node.getCreatedTime()|date('d/m/Y') }}
{# Resultado: 13/02/2020 #}
{{ [1, 2, 3]|join }}
{# Resultado: 123 #}
{{ [1, 2, 3]|join(',') }}
{# Resultado: 1,2,3 #}
{% set foo = [3, 2, 4, 1]|sort %}
{# El contenido de la variable for será: [1, 2, 3, 4] #}
{% set count = users|length %}
{# Almacena en la variable count el número de elementos de user #}
{{ 'Not triggered'|t }}
{% trans %}
Submitted by {{ author_name }} on {{ date }}
{% endtrans %}
{% set temp = 'The value is < 5' %}
{{ temp|placeholder }}
{# Imprime <em>This value is < 5</em> #}
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
{% for value, key in items %}
<div class="{{ key }}">{{ value }}</div>
{% endfor %}
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
{# Imprime 0, 1, 2, 3 #}
{% if title|length > 0 %}
<h1>{{ title }}</h1>
{% endif %}
Function De Drupal
{{ url('<front>') }}
{# Devuelve url absoluta#}
{{ path('mymodule.route') }}
{# Devuelve url relativa #}
{{ path('entity.user.canonical', {'user': user.id}) }}
{{ path('entity.node.canonical', {'node': node.id}) }}
{%- for item in items -%}
<li{{ item.attributes }}>
{{ link(item.title, item.url, {'class':['foo', 'bar']}) }}
</li>
{%- endfor -%}
{{ attach_library('classy/node') }}
{% for i in range(low=1, high=10, step=2) %}
{{ i }},
{% endfor %}
Para incluir plantillas hay que usar esta sintaxis en drupal:
{% include directory ~ '/templates/node-header.html.twig' %}
para pasarle parametros: https://twig.symfony.com/doc/3.x/functions/include.html
{% include directory ~ '/templates/button-social-media.html.twig' with {titulo_share: 'PIERRE'} %}
- En la plantilla "padre", o plantilla base, se pueden definir bloques mediante la etiqueta block
- Una plantilla "hija" puede heredar mediante {% extends "base.html.twig" %}
- Un block puede extender mediante {{ parent() }}
Ejemplo:
{# archivo base.html.twig #}
{% block head %}
Contenido head
{% endblock %}
{# archivo content.html.twig #}
{% extends "base.html.twig" %}
{% block head %}
{{ parent() }}
<link rel="stylesheet" href="css/custom.css" />
{% endblock %}
- Arrays
- ["foo", "bar", "barz"]
- Arrays asociativos
- { 'foo': 'foo', 'bar': 'bar' }
- { 2: 'foo', 4: 'bar' }
- Operaciones matemáticas
- +, -, /, % (resto) y *
- {{ 2 // 3 }} significa 2 / 3 y devuelve el numero entero redondeado
- {{ 2 ** 3 }} significa 2 elevado a 3
- Operadores lógicos
- and, or, not
- Operadores de comparación
- ==, !=, <, >, >= y <=
{% if 'foo' starts with 'f' %} {% endif %} {% if 'foo' ends with 'o' %} {% endif %} ```
- in
{% if 1 in [1, 2, 3] %}
{% if 5 not in [1, 2, 3] %}
{% if 'cd' in 'abcde' %}
- is
{% if value is odd %}
{% if post.status is constant('Post::PUBLISHED') %}
{% if post.status is not constant('Post::PUBLISHED') %}
Otros:
{{ 1..5 }}
{{ range(1, 5) }}
{{ (1..5)|join(', ') }}
{# Salida: 1, 2, 3, 4, 5 #}
{% set name = 'Fran' %}
{{ "Hello, " ~ name ~ "!" }}
{# Hello, Fran! #}
{{ foo ? 'yes' : 'no' }}
{{ foo ?: 'no' }} equivale a {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} equivale a {{ foo ? 'yes' : '' }}
Etiqueta spaceless
{% spaceless %}
<div>
<strong>foo bar</strong>
</div>
{% endspaceless %}
{# Salida: <div><strong>foo bar</strong></div> #}
<div id="{{ attributes.id }}" class="{{ attributes.class }}"{{ attributes }}>
{{ content }}
</div>