Controlador:
public function index()
{
$tabla=['a','b','c'];
$usuario="Juan";
$notas=[1,5,23,78,5];
$actores=['Penelope','Alec','Fernando'];
return $this->render('plantillas/index.html.twig', [
'tabla' => $tabla,
'usuario'=>$usuario,
'notas'=>$notas,
'actores'=>$actores
]);
}
Vista:
{% extends 'base.html.twig' %}
{% block body %}
{# funciones de twig #}
{{max(1,2,3)}}
{{max(tabla)}}
{{ random(['apple', 'orange', 'citrus']) }} {# example output: orange #}
{{ random('ABC') }} {# example output: C #}
{{ random() }} {# example output: 15386094 (works as the native PHP mt_rand function) #}
{{ random(5) }} {# example output: 3 #}
{{ random(10) }} {# example output: 3 #}
{{date()|date('d/m/Y')}}
{{date('2020-1-2')|date('d/m/Y')}}
{{date('-2days')|date('d/m/Y')}}
{{date('+2month')|date('d/m/Y')}}
{# filtros usando | (pipe) #}
{{usuario}}
{{usuario | upper}}
{{usuario | lower}}
{{usuario | reverse}}
{{tabla|sort|join(', ')|upper}}
{% set cadena='4,2,8,4,1,9,34' %}
{{cadena | split(',') |sort|join(',')}}
<table>
<tr><td>Nombre</td></tr>
{% for actor in actores %}
<tr><td>{{actor}}</td></tr>
{% endfor %}
</table>
{% set a=5 %}
{% set b=[1,2,3,4] %}
{% set c={'nombre':'Juan','Apellidos':'Pi'} %}
{{a +3}}
{{a * 3}}
{{a // 4}} {# division entera #}
{{a / 4}} {# division normal #}
{{a **2}} {# potencia (elevar a un número #}
{{a % 2}}
{% if a>10 %}
<h1>A es mayor que 10</h1>
{% else %}
<h1>A es menor que 10</h1>
{% endif %}
{% if a>10 %}
<h1>A es mayor que 10</h1>
{% elseif a>5 %}
<h1>A es menor que 5</h1>
{% else %}
<h1>A vale muy poco</h1>
<h2>Todo el código que quiera</h2>
{% endif %}
{# >,<,>=,<=,!=,==,===, starts width ends with matches #}
{% if usuario starts with 'J' %}
<p>Usuario empieza con j</p>
{% endif %}
{% if b[0] matches '/\\d+/' %}
<p>Es numérico</p>
{% endif %}
{% if 2 in b %}
<p>Tenemos 2 en b</p>
{% endif %}
{% if 2 is even %}
<p>Tenemos 2 en b</p>
{% endif %}
<ul>
{% for i in 0..10 if i is odd %}
<li>{{i}}</li>
{% endfor %}
{% for i in 'a'..'z' %}
<li>{{i}}</li>
{% endfor %}
{% for i in b %}
<li>{{i}}</li>
{% endfor %}
{% for i in tabla %}
<li>{{i}}</li>
{% endfor %}
</ul>
{% endblock %}