Richard Melo

@allucardster

Motor de plantillas TWIG

Agenda

  • Qué es TWIG?
  • Variables
  • Expresiones
  • Estructuras de control
  • Funciones
  • Filtros
  • Herencia de plantillas 

Qué es TWIG?

"Twig es un motor de plantillas para PHP, creado por Fabien Potencier en el 2009."

Caracteristicas

  • Rápido
  • Seguro
  • Flexible

Variables

{{ foo.bar }}
{{ foo['bar'] }}

Creando Variables

{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}

Expresiones

Literales

<!-- Strings -->
{{ "Hello World" }} {{ 'It\'s good' }}

<!-- Integers - Floats -->
{{ 42 }} {{ 42.5 }}

<!-- Arrays -->
["foo", "bar", 42, 42.5]

<!-- Hashes -->
{ 'foo': 'foo', 'bar': 'bar' }

{ foo: 'foo', bar: 'bar' }

{ 2: 'foo', 4: 'bar' }

{ (1 + 1): 'foo', 3: 'bar' }

<!-- Array and Hashes -->
{% set foo = [1, {"foo": "bar"}] %}

<!-- Others -->
{% set foo = true %}
{% set foo = false %}
{% set foo = null %}

Operadores Matemáticos

{{ 1 + 2 }} <!-- Adds two numbers -->
{{ 3 - 2 }} <!-- Substracts two numbers -->
{{ 1 / 2 }} <!-- Divide two numbers and return float -->
{{ 7 % 3 }} <!-- Calculate the remainder of division. -->
{{ 3 * 3 }} <!-- Multiplies two numbers -->
{{ 3 ** 3 }} <!-- Raises the left operand to the power of the right operand -->

Otros operadores

<!-- Containment Operator -->
{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

<!-- Not operator -->
{% 1 not in [1, 2, 3] %}

{% not (1 in [1, 2, 3]) %}

<!-- Is operator -->
{{ name is null }}

{{ name is not null }}

<!-- .. operator -->
{% set foo = 0..3 %}

<!-- ~ operator -->
{% set foo = 'World' %}
{% set foo = 1 %}
{{ 'Hello ' ~ foo ~ bar }}
<!-- . operator -->
{% set foo = { bar: 'Hello World' } %}

{{ foo.bar }}

<!-- [] operator -->
{% set foo = [1, 2, 3] %}

{{ foo[0] }}

{% set foo = { bar: [1, 2, 3] } %}
{{ foo['bar'][0] }}

<!-- String Interpolation -->
{% set foo = 'World' %}

{{ "Hello #{foo} }}

Estructuras de Control

Condicionales

{% if kenny.sick %}
    Kenny is sick.
{% elseif kenny.dead %}
    You killed Kenny! You bastard!!!
{% else %}
    Kenny looks okay --- so far
{% endif %}

Bucle For

{% for i in 0..10 %}
    {{ i }}
{% endfor %}

<!-- Loop variables -->

{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}


<!-- Loop with condition -->
<ul>
    {% for user in users if user.active %}
        <li>{{ user.username }}</li>
    {% endfor %}
</ul>

Comentarios

{# Lorem ipsum dolor sit amet, consectetur adipiscing elit. #}

{# Lorem ipsum dolor sit amet 
    {% set foo = 'bar' %}
#}

Funciones

{% set foo = range(0, 3) %}

<!-- With Variables -->

{% set foo = range(low=0, high=3) %}

Funciones principales

<!-- Date -->

{% if date(user.created_at) < date('-2days', 'Europe/Paris') %}
    {# do something #}
{% endif %}


<!-- Max -->

{# both print 3 #}

{{ max(1, 3, 2) }} 
{{ max([1, 3, 2]) }}

<!-- Min -->

{# both print 1 #}

{{ min(1, 3, 2) }}
{{ min([1, 3, 2]) }}

Filters

{# Basic syntax: var + 'pipe symbol' + filter name #}
{{ 'hello world'|upper }}

Filtros principales

<!-- Date Filter -->

{{ post.published_at|date("m/d/Y") }}
{{ post.published_at|date("m/d/Y", "Europe/Paris") }}

<!-- Convert encoding -->

{{ data|convert_encoding('UTF-8', 'iso-8859-1') }} {# utf8 to latin1 #}

<!-- Capitalize -->

{{ 'my first car'|capitalize }} {# print 'My First Car' #}

<!-- Length -->

{% if users|length > 10 %}
    {# do something #}
{% endif %}

<!-- nl2br -->

{{ "Lorem ipsum dolor sit amet\nconsectetur adipiscing elit."|nl2br }}

{#
    Lorem ipsum dolor sit amet<br >
    consectetur adipiscing elit.
#}

Herencia de plantillas

Bloques

{% block name %}
    <span>Richard</span>
{% endblock %}
<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="style.css" />
            <title>{% block title %}{% endblock %} - My Webpage</title>
        {% endblock %}
    </head>
    <body>
        <div id="content">{% block content %}{% endblock %}</div>
        <div id="footer">
            {% block footer %}
                © Copyright 2011 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
</html>

Template principal

{% extends "base.html" %}

{% block title %}Index{% endblock %}
{% block head %}
    {{ parent() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
        Welcome to my awesome homepage.
    </p>
{% endblock %}

Muchas Gracias

Made with Slides.com