You are on page 1of 2

Twig Sheets

Agence Web - iPhone & iPad Apps - Experts Symfony

Operators Control Structures


[not] in Containment operator FOR
is [not] Test operator
<ul>
.. Creates a sequence {% for item in collection %} <li>{{ item }}</li> {% endfor %}
| Applies a filter </ul>
~ Concatenation
. or [] Gets an attribute of an object {% for letter in 'a'..'z' %}
{{ letter }}
?: Ternary operator
{% endfor %}
{{ }} Used to print the result of an expression evalution
{% %} Used to execute statements
{% for i in 0..9 %}
{{ i }}
Variables {% endfor %}

Print {% for item in collection %}


{{ a_variable }} {{ item }}
{{ foo.bar }} {% else %}
{{ foo['bar'] }} No item.
{% endfor %}
Set
{% set value = 'foobar' %}
{% set foo = 'foo' %} {% for i in range(0,10,2) %}
{% set foo = [ 1, 2] %} {{ i }}
{% set foo = {'foo': 'bar'} %} {% endfor %}
{% set foo = 'foo' ~ 'bar' %}
{% set foo, bar = 'foo', 'bar' %} {% for item in collection %}
{{ loop.index }}
{% set value %} {% endfor %}
<div id="foobar">
... {% for key in items|keys %}
</div> {{ key }}
{% endset %} {% endfor %}

{% for key, item in items %}


{{ key }} : {{ item }}
Filters {% endfor %}

{{ foo|striptags }} loop.index The current iteration of the loop (1 indexed)


{% filter upper %}This text becomes uppercase{% endfilter %} loop.index0 The current iteration of the loop (0 indexed)
loop.revindex 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)
Comment loop.first True if first iteration
loop.last True if last iteration
{# single line comment #}
loop.length The number of items in the sequence
loop.parent The parent context
Whitespace Control IF
{% if foo %} {% if items %}
{% spaceless %} ... <ul>
<div> {% elseif bar %} {% for item in items %}
<strong>title</strong> ... <li>{{ item }}</li>
</div> {% else %} {% endfor %}
{% endspaceless %} ... </ul>
{# Output will be <div><strong>title</strong></div> #} {% endif %} {% endif %}

{% set value = 'Lorem Ipsum' %}


{{- value -}} Templates and Blocks
Define a block (redefine is existing)
<h1> {{- value }} </h1>
{# Will output <h1>Lorem Ipsum </h1> #} {% block sidebar %} ... {% endblock %}

Parent block
Macro
{% block sidebar %} {{ parent() }} {% endblock %}
{% macro link(url,label) %}
<a href="{{ url }}"> {{ label }}</a> Extends a template
{% endmacro %}
{% extends "base.html.twig" %}

{{ _self.link('index.html','Home') }} Include a template

{% import "forms.html" as forms %} {% include "header.html.twig" %}


{% from 'forms.html' import input as input_field %}
Include with access options
{{ form.input('foobar') }}
{{ input_field('foobar') }} {% include "header.html.twig" with { 'foo' : 'bar' } only %}

Import blocks from a template


Escaping {% use "blocks.html.twig" %}

{{ '{{' }} Import blocks with alias

{% raw %} {% use "blocks.html.twig" with sidebar as base_sidebar %}


{% set value = 'Lorem Ipsum' %}
<h1>{{ value }}</h1> Call a block
{% endraw %}
{{ block('base_sidebar') }}

Retrouvez-nous sur www.elao.com ou sur notre blog www.elao.org


Twig Sheets

Agence Web - iPhone & iPad Apps - Experts Symfony

Built-in Filters TWIG Extension


date Class
{{ post.created_at|date("d/m/Y") }}
{{ "now"|date("d/m/Y") }} class Project_Twig_Extension extends Twig_Extension
{
format // returns the unique name of the extension
{{ "I like %s and %s"|format(foo, 'bar') }} public function getName()
{
return 'project';
replace
{{ "Hello %name% !"|replace({'%name%': 'world'}) }} }

// returns an array of the implemented filters


url_encode URL encodes a given string.
public function getFilters()
json_encode Return the JSON representation of a given string. {
title Return a titlecased version of the value. return array(
capitalize Return a capitalized version of the value. 'myFilter' => new Twig_Filter_Method($this, 'myFilter')),
);
upper Convert a value to uppercase
}
lower Convert a value to lowercase
striptags Strips SGML/XML tags and replace adjacent whitespaces by one space. // exemple of a self-made filter
join public function myFilter($string)
{{ [a, b, c]|join(', ') }} {# return "a,b,c" #} {
{{ [a, b, c]|join }} {# return abc #} return '...' . $string . '...';
}
reverse Reverses an array or an object implementing the iterator interface
// retturns an array of global variables and functions
length Return the number of items of a sequence or array, or the length of a string
public function getGlobals()
sort Sort an array {
default return array(
{{ var|default('var is not defined') }} 'text' => new Text(),
'lipsum' => new Twig_Function(new Text(), 'getLipsum'),
keys );
{% for key in array|keys %} ... {% endfor %} }

escape, e Convert a string to HTML-safe sequences. // returns an array of implemented tests


raw Value will not be escaped public function getTests()
{
merge Merge an array with the value.
return array(
'even' => new Twig_Test_Function('twig_test_even'),
Built-in Tests }
);

divisibleby // returns an array of tags


{% if myNumber is divisibleby(2) %} ... {% endif %}
public function getTokenParsers()
{
none return array(new Project_Set_TokenParser());
{% if var is none %} ... {% endif %}
}

even // ...
{% if var is even %} ... {% endif %}
}

odd Registering extension


{% if var is odd %} ... {% endif %}
$twig = new Twig_Environement($loader);
sameas Check if a variable points to the same memory address than another. $twig->addExtension(new Project_Twig_Extension());

{% if var1 is sameas(var2) %} ... {% endif %} TWIG Extensions

constant Text :
{% if foo.var is constant('FOO::BAR') %} ... {% endif %} truncate, wordwrap and nl2br filters
I18N:
defined trans, transchoice filter
{% if var is defined %} ... {% endif %} Debug:
debug tag
empty
{% if var is empty %} ... {% endif %} # Load extension
$this->addExtension(new Twig_Extension_Text());

# add <br /> instead line break


Global Functions {{ content|nl2br }}

range # truncate at 20 words


{% for i in range(0, 3) %} {{ i }} {% endfor %} {{ content|wordwrap(20) }}
{# returns 0, 1, 2, 3 #}
# truncat at 20 characters
{% for i in range (0, 6, 2) %} {{ i }} {% endfor %} {{ content|truncate(20) }}

cycle # translate
{% for i in 0..10 %} {{ content|trans }}
{{ cycle(['odd', 'even'], i) }}
{% endfor %} # output when the debug environment option is set to true
{{ debug items }}
constant Returns the constant value for a given string. {{ debug foo.bar }}

{{ some_date|date(constant('DATE_W3C')) }}
Symfony2
Generate URL
Automatic Escaping
{{ path('route_name', {'param': 'value'}) }}
{% autoescape %}
Everything will be automatically escaped in this block Generate absolute URL
using the HTML strategy
{% endautoescape %} {{ url('route_name') }}

{% autoescape 'html' %} Link to Assets


Everything will be automatically escaped in this block
<link rel="stylesheet" href="{{ asset('css/style.css') }}" type="text/css" />
using the HTML strategy
<img src="{{ asset('images/logo.png') }}" alt="Logo" />
{% endautoescape %}

{% autoescape 'js' %} Registering extension


Everything will be automatically escaped in this block
<services>
using the js escaping strategy
<service id="acme.twig.acme_extension" class="Project_Twig_Extension">
{% endautoescape %}
<tag name="twig.extension" />
</service>
{% autoescape false %}
</services>
Everything will be outputted as is in this block
{% endautoescape %}

Retrouvez-nous sur www.elao.com ou sur notre blog www.elao.org

You might also like