Tuesday, May 28, 2013

Template : Twig - Basic

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


Global Variables
  _self : references the current template;
  _context : references the current context;
 _charset : references the current charset

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

Filters
  {{ name|striptags|title }}

  {{ list|join(', ') }}
  {% filter upper %}  
         This text becomes uppercase  
  {% endfilter %}

   built-in filter :
   abs / batch / capitalize / convert_encoding / date / date_modify / default /
   escape / first / format / join / json_encode / keys / last / length / lower / nl2br /
   number_format / merge / upper / raw / replace / reverse / slice / sort / split /
   striptags / title / trim / url_encode  


Functions
 {% for i in range(0, 3) %}
        {{ i }},  
 {% endfor %}

  built-in function :
   attribute / block / constant / cycle / date / dump /
   include / parent / random / range / template_from_string

{% for i in range(low=1, high=10, step=2) %}
    {{ i }},
{% endfor %}
 
 {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
 
 {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}






Control Structure

<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>
 
{% for i in 0..10 %}
    * {{ i }}
{% endfor %}
 
{% for letter in 'a'..'z' %}
    * {{ letter }}
{% endfor %} 
 
{% for letter in 'a'|upper..'z'|upper %}
    * {{ letter }}
{% endfor %} 
 
 
   for tags :
 



{% if users|length > 0 %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}


{% if online == false %}
    <p>Our website is in maintenance mode. Please, come back later.</p>
{% endif %} 
 
 
{% if users %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}


 
 
 
 
Including other Templates
 
 {% include 'sidebar.html' %} 
 
 {% for box in boxes %}
    {% include "render_box.html" %}
{% endfor %}


 

{% include "sections/articles/sidebar.html" %}



Template Inheritance (block)

base.html (4 block)

<!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 %}
                &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
</html>
 
 Child tepmalte :
 
{% 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 %}
 
 
extends - using parent() function
 
{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ parent() }}
{% endblock %} 
 
 


HTML Escaping (using piping)

{{ user.username|escape }} 
{{ user.username|e }}

{{ user.username|e('js') }}
{{ user.username|e('css') }}
{{ user.username|e('url') }}
{{ user.username|e('html_attr') }}

{% autoescape %}
    Everything will be automatically escaped in this block (using the HTML strategy)
{% endautoescape %}
 
{{ '{{' }}

{% macro input(name, value, type, size) %}
    <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
{% endmacro %}

{% import "forms.html" as forms %}
<p>{{ forms.input('username') }}</p>


{% from 'forms.html' import input as input_field %}

<dl>
    <dt>Username</dt>
    <dd>{{ input_field('username') }}</dd>
    <dt>Password</dt>
    <dd>{{ input_field('password', '', 'password') }}</dd>
</dl>


{% macro input(name, value = "", type = "text", size = 20) %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" />
{% endmacro %}



Expressions
 operator precedence :
  b-and, b-xor, b-or, or, and, ==, !=, <, >, >=, <=, in, .., +, -, ~, *, /, //, %, is, **, |, [], and .:


{% set greeting = 'Hello' %}
{% set name = 'Fabien' %}

{{ greeting ~ name|lower }}   {# Hello fabien #}

{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}


{# keys as string #}
{ 'foo': 'foo', 'bar': 'bar' }

{# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
{ foo: 'foo', bar: 'bar' }

{# keys as integer #}
{ 2: 'foo', 4: 'bar' }

{# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
{ (1 + 1): 'foo', (a ~ 'b'): 'bar' }


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

Math

 + : {{ 1 + 1 }} is 2. 
 - : {{ 3 - 2 }} is 1. 
 / : The returned value will be a floating point number. {{ 1 / 2 }} is {{ 0.5 }}. 
 % : {{ 11 % 7 }} is 4. 
 //: Divides and returns the truncated integer result. {{ 20 // 7 }} is 2. 
 * : {{ 2 * 2 }} would return 4. 
 **: power of the right operand. {{ 2 ** 3 }} would return 8.

Logic

 and , or , not , (expr)


Comparisons

==, !=, <, >, >=, and <=



Containment Operator

{# returns true #}
{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}
 
{% if 1 not in [1, 2, 3] %}

{# is equivalent to #}
{% if not (1 in [1, 2, 3]) %}

Test Operator

{# find out if a variable is odd #}
{{ name is odd }}
{% if loop.index is divisibleby(3) %} 
{# is equivalent to #}
{% if not (loop.index is divisibleby(3)) %}


Other Operators
  ..    :  range 
  |    : Applies a filter. 
  ~      : Converts into strings and concat. 
  ., [] : Gets an attribute of an object. 
  ?:    : The ternary operator


{{ foo ? 'yes' : 'no' }}

{# as of Twig 1.12.0 #}
{{ foo ?: 'no' }} == {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} == {{ foo ? 'yes' : '' }}

String Interpolation

{{ "foo #{bar} baz" }}
{{ "foo #{1 + 2} baz" }}

Whitespace Control


{% spaceless %}
    <div>
        <strong>foo</strong>
    </div>
{% endspaceless %}

{# output will be <div><strong>foo</strong></div> #} 
 
{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
    {{- value -}}
{%- endif -%}

{# output 'no spaces' #}
 
{% set value = 'no spaces' %}
<li>    {{- value }}    </li>

{# outputs '<li>no spaces    </li>' #} 
 
 
 









Global Tempalate :

  • app.security - The security context.
  • app.user - The current user object.
  • app.request - The request object.
  • app.session - The session object.
  • app.environment - The current environment (dev, prod, etc).
  • app.debug - True if in debug mode. False otherwise.

No comments:

Post a Comment