0% found this document useful (0 votes)
3 views76 pages

Slides

Twig is a modern template engine for PHP that offers features such as fast performance, security through automatic content escaping, and a modern syntax. It allows for concise code with template-oriented syntax and supports advanced functionalities like filters, functions, and control structures. Twig also supports template inheritance and macros, making it a powerful tool for web application development.

Uploaded by

wvan444
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views76 pages

Slides

Twig is a modern template engine for PHP that offers features such as fast performance, security through automatic content escaping, and a modern syntax. It allows for concise code with template-oriented syntax and supports advanced functionalities like filters, functions, and control structures. Twig also supports template inheritance and macros, making it a powerful tool for web application development.

Uploaded by

wvan444
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to

Twig

SensioLabs
What is Twig
What is Twig
Twig is a modern template engine for
PHP.
The official website for the project is
[Link]
This is the official logo of the project

In English, twig literally means


«A small thin branch of a tree or bush»
Twig features
• Fast
Templates are compiled to raw PHP before executing them
• Secure
By default, contents are escaped before displaying them. It
also includes a sandbox mode to restrict template execution
• Modern
Template-oriented syntax, concise, flexible and full-
featured for modern web application
Twig is more concise than PHP
{{ variable }} Twig is secure by default
because it escapes contents
before displaying them.
<?php
echo htmlspecialchars(
$variable,
ENT_QUOTES, Secure PHP code is much
'UTF-8' more verbose.
)
?>
Twig's template oriented syntax
{% for user in users %}
* {{ [Link] }}
{% else %}
No users have been found.
{% endfor %}
for ... else is a convenient
construct provided by Twig and
which doesn't exist in PHP
Basic
syntax
Concise syntax
{# ... comment something ... #}

{% ... do something ... %}

{{ ... display something ... }}

These are the three special tags used to separate Twig code
from regular template contents.
Rendering
variables
Abstracting access to variables

{{ [Link] }}

Twig templates use the "dot syntax" to access properties from


PHP objects and associative arrays.
Abstracting access to variables
echo $article['title'];
echo $article->title;
echo $article->title();
echo $article->getTitle();
echo $article->isTitle();
echo $article->hasTitle();
When using {{ [Link] }} in a template, Twig will look for
these keys/properties/methods and in this order.
Strict variables
# config/packages/[Link] Fails silently when the
twig:
strict_variables: false
variable doesn't exist
(page shows a blank spot)
{{ [Link] }}

# config/packages/[Link] Throws an exception


twig:
strict_variables: true when the variable doesn't
exist.
{{ [Link] }}
Filters and
functions
Filters format contents
{{ [Link]|date('d/m/Y') }}

{{ [Link]|lower }}
{{ [Link]|upper }}
{{ [Link]|capitalize }}
{{ [Link]|title }}

{{ [Link]|sort|join(', ') }}

{{ [Link]|default('Anonymous') }}
Built-in filters
• abs • join • replace
• batch • json_encode • reverse
• capitalize • keys • slice
• convert_encoding • last • sort
• date • length • split
• date_modify • lower • striptags
• default • merge • title
• escape • nl2br • trim
• first • number_format • upper
• format • raw • url_encode

Official Twig documentation: [Link]/documentation


Functions generate contents
Hi {{ random(['John', 'Tom', 'Paul']) }}!

{% for i in range(0, 10, 2) %}


{{ cycle(['odd', 'even'], i) }} <br/>
{% endfor %}
Built-in functions
• attribute • dump • random
• block • include • range
• constant • max • source
• cycle • min • template_fr
• date • parent om_string

Official Twig documentation: [Link]/documentation


Output
escaping
Automatic output escaping

Hi {{ name }}!

The variable name is automatically


escaped if it contains a string
Automatic output escaping

Hi {{ name }}
$name = '<strong>John</strong>';
Automatic output escaping
Expected output
Hi <strong>John</strong>

Hi John
Automatic output escaping
Real output
Hi &lt;strong&gt;John&lt;/strong&gt;

Hi <strong>John</strong>
Control
structures
Comparison of control structures
Twig PHP
if else break for
elseif for continue foreach
do ... while goto
if switch
elseif while
else
Making decisions
{% if [Link] > 10 %}
Available
{% elseif [Link] > 0 %}
Only {{ [Link] }} left!
{% else %}
Sold-out!
{% endif %}
Iterating over a collection
{% for post in posts if [Link] %}
<h2>{{ [Link] }}</h2>
{{ [Link] }}
{% else %}
No published posts yet.
{% endfor %}

The if statement filters the collection before iterating


over it with the for statement.
The loop context
Variable Description
[Link] The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
[Link] The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
[Link] True if first iteration
[Link] True if last iteration
[Link] The number of items in the sequence
[Link] The parent context
Operators
Basic operators
Mathematical
+ - * / ** // %

Logical
and or not ( ... )
b-and b-xor b-or
Comparison operators
== != < > <= >=

starts with ends with matches


{% if url starts with '[Link] %}

{% if fileName ends with '.txt' %}

{% if phone matches '/^[\d\.]+$/' %}


Concatenation operator
~
{{ 'Hello ' ~ [Link] ~ '!' }}

{{ firstName ~ ' ' ~ lastName }}


Interpolation operator
#{ }

{{ 'Hello #{ [Link] }!' }}

{{ 'Discount: #{ [Link] *
discount / 100 }' }}
Containment operator
in not in
{% if name not in [Link] %}
Add as a friend
{% endif %}

{% if login in password %}
ERROR password can't contain login!
{% endif %}
Other operators
is is not

{% if number is odd %}
{% if number is not
divisible by(3) %}
Built-in tests
{% if numElements is constant('Object::CONSTANT') %}
{% if [Link] is defined %}
{% if [Link]|length is divisible by(3) %}
{% if [Link] is empty %}
{% if [Link]|length is even %}
{% if [Link]|length is odd %}
{% if [Link] is iterable %}
{% if user is null %}
{% if user is same as(logged_user) %}

Check out the official Twig reference at [Link]


Other operators
..
{% if number in 1..10 %}

{% for letter in 'a'..'z' %}

Equivalent to PHP range() function, but more concise.


Other operators
? ?: ??
{{ [Link] ? 'yes' : 'no' }}
{{ [Link] ?: 'Anonymous' }}
<div class="{{ category == 'index' ? 'active' }}">

{{ num_items ?? 0 }}
Whitespace
control
Whitespace control
{% spaceless %}
<p>
Hello <strong>{{ name }}</strong>!
</p>
{% endspaceless %}

<p>Hello <strong>Hugo</strong>!</p>
Whitespace control
<p>
Hello <strong> {{- name }} </strong>!
</p>

<p>Hello <strong>Hugo </strong>!</p>


Whitespace control in practice
<ul>
{% for i in 1..3 %}
<li>{{ i }}</li>
{% endfor %}
</ul> <ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Whitespace control in practice
<ul>
{% for i in 1..3 %}
<li>{{ i }}</li>
{% endfor %}
</ul> <ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Whitespace control in practice
<ul>
{%- for i in 1..3 %}
<li>{{ i }}</li>
{% endfor %}
</ul>
<ul> <li>1</li>
<li>2</li>
<li>3</li>
</ul>
Whitespace control in practice
<ul>
{%- for i in 1..3 -%}
<li>{{ i }}</li>
{% endfor %}
</ul>
<ul><li>1</li>
<li>2</li>
<li>3</li>
</ul>
Whitespace control in practice
<ul>
{%- for i in 1..3 -%}
<li>{{ i }}</li>
{%- endfor -%}
</ul>

<ul><li>1</li><li>2</li><li>3</li></ul>
Whitespace control in practice
{% spaceless %}
<ul>
{% for i in 1..3 %}
<li>{{ i }}</li>
{% endfor %}
</ul>
{% endspaceless %}

<ul><li>1</li><li>2</li><li>3</li></ul>
Template
inclusion
Template inclusion
The include() function evaluates a
template and returns the generated
contents.

<header>
{{ include('[Link]') }}
</header>
Template inclusion
The included template can be stored
anywhere in your application:

<header>
{{ include('common/[Link]') }}
</header>
Variable scope
• Included templates can access to all the
parent template's variables.
• Use with_context option to control this.
<header>
{{ include('common/[Link]',
with_context = false) }}
</header>
Passing new variables or renaming them
<header>
{{ include(
'common/[Link]',
{ var1: '...', var2: '...' },
with_context = false
) }}
</header>
Template
inheritance
The need of template inheritance
• In a given website, most of its pages
share the same structure.
• Using the include() function is possible,
but inefficient.
• Template inheritance is the best way to
solve this problem.
Creating the parent template
Contains all the common HTML elements shared by all pages and defines
the blocks of contents that can be filled in by child templates.
{# app/Resources/views/[Link] #}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My website</title>
</head>
<body>
<h1>My Symfony Application</h1>
{% block body %}{% endblock %}
</body>
</html>
Creating the child template
{% extends '[Link]' %}

{% block body %}
<h2>Latest posts</h2>
{{ include('[Link]') }}
{% endblock %}
Extending from the parent template
{% extends '[Link]' %}

• It must be the first instruction of the template.


• A template can only inherit from one template.
• There is no inheritance level limit (parent, child,
grandchild, etc.)
Filling the parent's blocks
{% block body %}
<h2>Latest posts</h2>
{{ include('[Link]') }}
{% endblock body %}

• Child templates can fill-in the blocks defined in the


parents, but it's not mandatory to do it.
• Child templates cannot add content outside a block
element. Otherwise, Twig will show an error.
• Inside a block content you can use any Twig element,
including expressions and include() function.
Parent templates usually define lots of blocks
{# templates/[Link] #}
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>{% block title %}{% endblock %}</title>
</head>

<body id="{% block body_id %}{% endblock %}">


<h1>My Symfony Application</h1>
{% block body %}{% endblock %}
</body>

</html>
Child templates usually fill most of the blocks
{% extends '[Link]' %}

{% block body_id %}blog_index{% endblock %}


{% block title %}Blog{% endblock %}

{% block body %}
<h2>Latest posts</h2>
{{ include('[Link]') }}
{% endblock body %}
Alternative notation for short blocks
{% extends '[Link]' %}

{% block body_id 'blog_index' %}


{% block title 'Blog' %}

{% block body %}
<h1>Latest posts</h1>
{{ include('[Link]') }}
{% endblock body %}
Reusing the content of any block
{% extends '[Link]' %}

{% block body_id 'blog_index' %}


{% block title 'Blog' %}

{% block body %}
<h1>{{ block('title') }}</h1>
{{ include('[Link]') }}
{% endblock body %}
Parent templates can define default contents
{# templates/[Link] #}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
{% block title %}My application{% endblock %}
</title>
</head>

<body id="{% block body_id %}{% endblock %}">


<h1>My Symfony Application</h1>
{% block body %}{% endblock %}
</body>
</html>
Default contents in child templates
{% extends '[Link]' %}

{% block title %} Removes


{% endblock %} the default parent value

{% block title %}
Blog Overrides
the default parent value
{% endblock %}

{% block title %}
Blog - {{ parent() }} Modifies
the default parent value
{% endblock %}
Macros
What is a Twig macro
• Macros are comparable with functions in
regular programming languages.
• They are useful to put often used HTML
idioms into reusable elements to not
repeat yourself.
• They must be imported before using them.
Defining a macro
{% macro input(name, value, type='text', size=20) %}
<input type="{{ type }}"
name="{{ name }}"
value="{{ value|e }}"
size="{{ size }}" />
{% endmacro %}
Using a macro defined in an external file
{% import "form_macros.[Link]" as utils %}

<form>
{{ [Link]('username') }}
{{ [Link]('password', null, 'password') }}
</form>
Using a macro defined in the same file
{% macro input(name, value, type = 'text', size = 20) %}
<input type="{{ type }}" name="{{ name }}"
value="{{ value|e }}" size="{{ size }}" />
{% endmacro %}

{% import _self as utils %}

<form>
{{ [Link]('username') }}
{{ [Link]('password', null, 'password') }}
</form>
Debug
Accurate error messages
{{ rand(['A', 'B', 'C', 'D']) }}!

Twig_Error_Syntax

The function "rand" does not exist. Did you mean


"random" in "[Link]" at line 3
Dumping variables
{% set names = ['John', 'Tom', 'Paul'] %}
{% set numbers = 1..5 %}

{{ dump(names) }}
{{ dump(names, numbers) }}

{{ dump() }}
dumps every variable that
exists in the template
PHP
compilation
PHP compilation process
• To increase performance, Twig
templates are compiled down to PHP.
• The impact on performance over raw
PHP templates is negligible.
• In development, changed templates are
recompiled. Not in production.
A simple Twig template

{# A comment #}
Hello {{ name }}!
The resulting PHP compiled template
/* templates/[Link] */
class __TwigTemplate_d2793ba4e21454af9bfe3bc75aaa83b5324a893143a805c121808f3902a38ca6
extends Twig_Template {
public function __construct(Twig_Environment $env) { ... }

protected function doDisplay($context, $blocks = array()) {


// line 2
echo "Hello ";
echo twig_escape_filter($this->env, (isset($context["name"]) ?
$context["name"] : $this->getContext($context, "name")), "html", null,
true);
echo "!";
}

// ...
}
SensioLabs

You might also like