Twig Templating

John Rudolph Bautista
Software Engineer

The Twig logo is © Sensio Labs

October 26th 2013
PHP AS TEMPLATE
Why TWIG
WAS
born?
WAYBACK 2009
FABIEN potencier
- Symfony
- SwiftMailer
- Silex
- Pimple
- Twig
…. many more
https://github.com/fabpot
TWIG
The Twig logo is © Sensio Labs
Twig
- Provides Pattern Consistency
- Solves Complex Control Flow
- Template Inheritance & Macros
- Fully Extendable
Twig
- Well Documented
- Unit Tested
- Secure
- Fast (has a caching layer by default)
Syntax Highlighting
Installation
VIa Composer
VIA Composer

http://getcomposer.org/
VIA TARBALL OR ZIP
https://github.com/fabpot/Twig/tags
- Unpack
- Move files to your project folder
VIA GIT
https://github.com/fabpot/Twig/tags
git clone git://github.com/fabpot/Twig.git
USING TWIG API
Delimiters
{{ ... }}
- displays something

{% ... %}
- evaluates an expression (loops, tags, cond.)

{# ... #}
- comments code blocks
Twig Template FILE
Twig Template FILE
← Comment
Twig Template FILE
← FILTER
Twig Template FILE
← TAG
Twig Template FILE

← VARIABLE
Twig Template FILE

← FILTER WITH
ARGUments
THE BASICS
LITERALS
String = “Manong Johny”
Integer = 100000000
Float = 100000000.00
Array = [“pdaf”, “dap”]
Hash = {“key” : “value”}
Boolean = true/false
Null = null
SETTING VARIABLES
{% set str = 'value' %}
{% set arr = [1, 2, 3] %}
{% set hash = {'a' : 1, 'b': 2 } %}
{% set combine = ['a' : { 'b': 2 }] %}
PRINTING VARIABLES
{{ var }}
{{ var['elem'] }}
{{ var.elem }}
{{ var.prop }}
FILTERS
- Modifies a variable
- Uses “|” (pipe)
- Chainable
- Can accept arguments
FILTERS
{{ employee|title }}
Result : “Janet Napoles”
{{ tags|join(', ') }}
Result : “ph, rich, more fun”
MACROS
- acts like functions in regular
programming language
- default argument values are defined
by using the default() filter
- arguments are always optional
MACROS
ESCAPING
- escapes a string for safe insertion
into the final output
{{ var|escape }}
{{ var|e }}
{% autoescape %}
….
{% endautoescape %}
ESCAPING
Default Escape : {{ str|escape }}
<p>Hello World!</p>
JS Escape : {{ str|escape('js ') }}
x3Cpx3EHellox20Worldx21x3Cx2Fpx3E
CSS Escape : {{ str|escape('css ') }}
3C p3E Hello20 World21 3C 2F p3E
URL Escape: {{ str|escape('url') }}
%3Cp%3EHello%20World%21%3C%2Fp%3E
IF, ELSEIF, ELSE
FOR LOOP
- loop each item in a sequence
FOR LOOP
FOR WITH CONDITION
FOR LOOP VARIABLES
TEMPLATE
INHERITANCE
BLOCK
- are used for inheritance and act
as placeholders and replacements.
{% block content %}
…..
{% endblock %}
NAMED BLOCK END-TAGS
EXTENDS
- can be used to extend a template
from another one.
{% extends “layout.twig” %}
EXTENDS & BLOCK
EXTENDS & BLOCK
EXTENDS & BLOCK

{% block content %}

{% endblock content %}
INCLUDE
- includes a template and return
the rendered content of that file
into the current namespace.
INCLUDE
INCLUDE
DRUPAL

+

TWIG
Drupal 8 & Twig Road Map : http://lb.cm/twig
<THANK
YOU!

Twig Templating