Twig常用语法

原链接:https://twig.symfony.com/doc/2.x/templates.html

概要

twig 的模板就是普通的文本文件,也不需要特别的扩展名,.html .htm .twig 都可以。

模板内的 变量 和 表达式 会在运行的时候被解析替换,标签(tags)会来控制模板的逻辑

下面是个最小型的模板,用来说明一些基础的东西

[html] view plaincopyprint?

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title>My Webpage</title>  
  5.     </head>  
  6.     <body>  
  7.         <ul id="navigation">  
  8.         {% for item in navigation %}  
  9.             <li><a href="{{ item.href }}">{{ item.caption }}</a></li>  
  10.         {% endfor %}  
  11.         </ul>  
  12.   
  13.         <h1>My Webpage</h1>  
  14.         {{ a_variable }}  
  15.     </body>  
  16. </html>  


里面包含两种符号 {% ... %} 和 {{ ... }} 第一种用来控制的比如for循环什么的,第二个是用来输出变量和表达式的

 

ide 支持

很多ide 都对twig进行高亮支持。大伙自己找需要的吧。

变量

程序会传递给模板若干变量,你需要在模板里输出他们。例如输出 $hello

[html] view plaincopyprint?

  1. {{ hello }}  

如果传递给模板的是对象或者数组,你可以使用点 . 来输出对象的属性或者方法,或者数组的成员。或者你可以使用下标的方式。

[html] view plaincopyprint?

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


如果你访问的值不存在就会返回null。TWIG有一整套的流程来确认值是否存在。

 

for.bar会进行以下操作

。。。如果 foo是个数组,就尝试返回bar成员,如果不存在的话,往下继续

。。。如果foo是个对象,会尝试返回bar属性,如果不存在的话,往下继续

。。。会尝试运行bar方法,如果不存在的话,往下继续

。。。会尝试运行getBar方法,如果不存在的话,往下继续

。。。会尝试运行isBar方法,如果不存在的话,返回null

 

for['bar'] 就简单很多了 for必须是个数组,尝试返回bar成员,如果不就返回null

全局变量

TWIG定义了有一些全局变量

  • _self  这个参看macro标签
  • _context 这个就是当前的环境
  • _charset: 当前的字符编码

 

变量赋值

具体参见set标签

[html] view plaincopyprint?

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

 

过滤器 Firters

变量可以被过滤器修饰。过滤器和变量用(|)分割开。过滤器也是可以有参数的。过滤器也可以被多重使用。

下面这例子就使用了两个过滤器。

[html] view plaincopyprint?

  1. {{ name|striptags|title }}  

striptas表示去除html标签,title表示每个单词的首字母大写。更多过滤器参见我博客

 

过滤器也可以用在代码块中,参见 filter标签

[html] view plaincopyprint?

  1. {% filter upper %}  
  2.   This text becomes uppercase  
  3. {% endfilter %}  

 

函数 Function

这个没什么好说的,会写程序的都知道,TWIG内置了一些函数,参考我的博客

举个例子 返回一个0到3的数组,就使用 range函数

[html] view plaincopyprint?

  1. {% for i in range(0, 3) %}  
  2.     {{ i }},  
  3. {% endfor %}  

 

流程控制

支持for循环 和 if/elseif/else结构。直接看例子吧,没什么好说的。

[html] view plaincopyprint?

  1. <h1>Members</h1>  
  2. <ul>  
  3.     {% for user in users %}  
  4.         <li>{{ user.username|e }}</li>  
  5.     {% endfor %}  
  6. </ul>  

[html] view plaincopyprint?

  1. {% if users|length > 0 %}  
  2.     <ul>  
  3.         {% for user in users %}  
  4.             <li>{{ user.username|e }}</li>  
  5.         {% endfor %}  
  6.     </ul>  
  7. {% endif %}  

 

注释

{# ... #} 包围的内容会被注释掉,可以是单行 也可以是多行。

 

载入其他模板

详见include标签(我博客内已经翻译好哦),会返回经过渲染的内容到当前的模板里

[html] view plaincopyprint?

  1. {% include 'sidebar.html' %}  

当前模板的变量也会传递到 被include的模板里,在那里面可以直接访问你这个模板的变量。

比如

[html] view plaincopyprint?

  1. {% for box in boxes %}  
  2.     {% include "render_box.html" %}  
  3. {% endfor %}  

在 render_box.html 是可以访问 box变量的
加入其他参数可以使被载入的模板只访问部分变量,或者完全访问不到。参考手册

 

模板继承

TWIG中最有用到功能就是模板继承,他允许你建立一个“骨骼模板”,然后你用不同到block来覆盖父模板中任意到部分。而且使用起来非常到简单。

我们先定义一个基本骨骼页base.html 他包含许多block块,这些都可以被子模板覆盖。

[html] view plaincopyprint?

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         {% block head %}  
  5.             <link rel="stylesheet" href="style.css" />  
  6.             <title>{% block title %}{% endblock %} - My Webpage</title>  
  7.         {% endblock %}  
  8.     </head>  
  9.     <body>  
  10.         <div id="content">{% block content %}{% endblock %}</div>  
  11.         <div id="footer">  
  12.             {% block footer %}  
  13.                 © Copyright 2011 by <a href="http://domain.invalid/">you</a>.  
  14.             {% endblock %}  
  15.         </div>  
  16.     </body>  
  17. </html>  

我们定义了4个block块,分别是 block head, block title, block content, block footer 

注意

1、block是可以嵌套的。

2、block可以设置默认值(中间包围的内容),如果子模板里没有覆盖,那就直接显示默认值。比如block footer ,大部分页面你不需要修改(省力),但你需要到时候仍可以方便到修改(灵活)

下面我看下 子模板应该怎么定义。

[html] view plaincopyprint?

  1. {% extends "base.html" %}  
  2.   
  3. {% block title %}Index{% endblock %}  
  4. {% block head %}  
  5.     {{ parent() }}  
  6.     <style type="text/css">  
  7.         .important { color: #336699; }  
  8.     </style>  
  9. {% endblock %}  
  10. {% block content %}  
  11.     <h1>Index</h1>  
  12.     <p class="important">  
  13.         Welcome on my awesome homepage.  
  14.     </p>  
  15. {% endblock %}  

注意 {% extends "base.html" %} 必须是第一个标签。其中 block footer就没有定义,所以显示父模板中设置的默认值

如果你需要增加一个block的内容,而不是全覆盖,你可以使用 parent函数

[html] view plaincopyprint?

  1. {% block sidebar %}  
  2.     <h3>Table Of Contents</h3>  
  3.     ...  
  4.     {{ parent() }}  
  5. {% endblock %}  


extends标签只能有一个,所以你只能有一个父模板,但有种变通到方法来达到重用多个模板到目的,具体参见手册的use标签

 

HTML转义

主要是帮助转义 尖括号等  <, >,  &,  "  可以有两种办法。一种是用标签,另一种是使用过滤器。其实TWIG内部就是调用 php 的htmlspecialchars 函数

[html] view plaincopyprint?

  1. {{ user.username|e }}  
  2. {{ user.username|e('js') }}  
  3.   
  4. {% autoescape true %}  
  5.     Everything will be automatically escaped in this block  
  6. {% endautoescape %}  


因为{{是TWIG的操作符,如果你需要输出两个花括号,最简单到办法就是

[html] view plaincopyprint?

  1. {{ '{{' }}  


还可以使用 raw 标签和raw 过滤器,详细参考手册

[html] view plaincopyprint?

  1. {% raw %}  
  2.     <ul>  
  3.     {% for item in seq %}  
  4.         <li>{{ item }}</li>  
  5.     {% endfor %}  
  6.     </ul>  
  7. {% endraw %}  

 

macros宏

宏有点类似于函数,常用于输出一些html标签。

这里有个简单示例,定义了一个输出input标签的宏。

[html] view plaincopyprint?

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

宏参数是没有默认值的,但你可以通过default过滤器来实现。

一般来说宏会定义在其他到页面,然后通过import标签来导入,

[html] view plaincopyprint?

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

你也可以只导入一个文件中部分宏,你还可以再重命名。

[html] view plaincopyprint?

  1. {% from 'forms.html' import input as input_field, textarea %}  
  2.   
  3. <dl>  
  4.     <dt>Username</dt>  
  5.     <dd>{{ input_field('username') }}</dd>  
  6.     <dt>Password</dt>  
  7.     <dd>{{ input_field('password', type='password') }}</dd>  
  8. </dl>  
  9. <p>{{ textarea('comment') }}</p>  

上面的代码表示 从forms.html中导入了 input 和 textarea宏,并给input重命名为input_field。

表达式

TWIG允许你在任何地方使用表达式,他的规则和PHP几乎一模一样,就算你不会PHP 仍然会觉得很简单。

最简单的有 

字符串:“hello world”  或者 'hello world'  

数字:42 或者 42.33

数组:['a','b','c']

哈希:{'a':'av', 'b':'bv'} 其中keys 可以不要引号 也可以是数字 还可以是一个表达式,比如{a:'av', b:'bv'}  {1:'1v', 2:'2v'}  {1+2:'12v'}

逻辑: true 或者 false

最后还有null

你可以嵌套定义

[html] view plaincopyprint?

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

运算符

包括数字运算+ - * /  %(求余数)  //(整除) **(乘方)

[html] view plaincopyprint?

  1. <p>{{ 2 * 3 }}=6  
  2. <p>{{ 2 * 3 }}=8  

逻辑运算 and or  not

比较运算 > < >= <= == !=

包含运算 in 以下的代码会返回 true

[html] view plaincopyprint?

  1. {{ 1 in [1, 2, 3] }}  
  2. {{ 'cd' in 'abcde' }}  

测试运算 is 这个不用多说 直接看代码

[html] view plaincopyprint?

  1. {{ name is odd }}  
  2. {% if loop.index is divisibleby(3) %}  
  3. {% if loop.index is not divisibleby(3) %}  
  4. {# is equivalent to #}  
  5. {% if not (loop.index is divisibleby(3)) %}  

其他操作符

.. 建立一个指定开始到结束的数组,他是range函数的缩写,具体参看手册

[html] view plaincopyprint?

  1. <pre name="code" class="html">{% for i in 0..3 %}  
  2.     {{ i }},  
  3. {% endfor %}</pre>  
  4. <pre></pre>  

| 使用一个过滤器

[html] view plaincopyprint?

  1. {# output will be HELLO #}  
  2. {{ "hello"|upper }}  

~ 强制字符串连接

[html] view plaincopyprint?

  1. {{ "Hello " ~ name ~ "!" }}  

?:  三元操作符

[html] view plaincopyprint?

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

. [] 得到一个对象的属性,比如以下是相等的。

[html] view plaincopyprint?

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


你还可以在一个字符串内部插入一个表达式,通常这个表达式是变量。 格式是 #{表达式}

[html] view plaincopyprint?

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

 

空白控制

和 php一样,在TWIG模板标签之后的第一个换行符会被自动删掉,其余的空白(包括 空格 tab 换行等)都会被原样输出。

使用spaceless标签就可以删除这些HTML标签之间的空白

[html] view plaincopyprint?

  1. {% spaceless %}  
  2.     <div>  
  3.         <strong>foo</strong>  
  4.     </div>  
  5. {% endspaceless %}  
  6.   
  7. {# output will be <div><strong>foo</strong></div> #}  


使用-操作符,可以很方便的删除TWIG标签之前或之后与html标签之间的空白。

[html] view plaincopyprint?

  1. {% set value = 'no spaces' %}  
  2. {#- No leading/trailing whitespace -#}  
  3. {%- if true -%}  
  4.     {{- value -}}  
  5. {%- endif -%}  
  6.   
  7. {# output 'no spaces' #}  

[html] view plaincopyprint?

  1. {% set value = 'no spaces' %}  
  2. <li>    {{- value }}    </li>  
  3.   
  4. {# outputs '<li>no spaces    </li>' #}  

 

结束,如果你坚持看到这里,恭喜自己吧,你又多掌握了一些知识,恭喜恭喜

原页:

Twig for Template Designers

This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Twig templates.

Synopsis

A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). It doesn't have a specific extension, .html or .xml are just fine.

A template contains variables or expressions, which get replaced with values when the template is evaluated, and tags, which control the logic of the template.

Below is a minimal template that illustrates a few basics. We will cover further details later on:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
    <head>
        <title>My Webpage</title>
    </head>
    <body>
        <ul id="navigation">
        {% for item in navigation %}
            <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
        {% endfor %}
        </ul>

        <h1>My Webpage</h1>
        {{ a_variable }}
    </body>
</html>

There are two kinds of delimiters: {% ... %} and {{ ... }}. The first one is used to execute statements such as for-loops, the latter prints the result of an expression to the template.

IDEs Integration

Many IDEs support syntax highlighting and auto-completion for Twig:

Also, TwigFiddle is an online service that allows you to execute Twig templates from a browser; it supports all versions of Twig.

Variables

The application passes variables to the templates for manipulation in the template. Variables may have attributes or elements you can access, too. The visual representation of a variable depends heavily on the application providing it.

You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called "subscript" syntax ([]):

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

When the attribute contains special characters (like - that would be interpreted as the minus operator), use the attribute function instead to access the variable attribute:

1
2
{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}

It's important to know that the curly braces are not part of the variable but the print statement. When accessing variables inside tags, don't put the braces around them.

If a variable or attribute does not exist, you will receive a null value when the strict_variables option is set to false; alternatively, if strict_variables is set, Twig will throw an error (see environment options).

Implementation

For convenience's sake foo.bar does the following things on the PHP layer:

  • check if foo is an array and bar a valid element;
  • if not, and if foo is an object, check that bar is a valid property;
  • if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
  • if not, and if foo is an object, check that getBar is a valid method;
  • if not, and if foo is an object, check that isBar is a valid method;
  • if not, and if foo is an object, check that hasBar is a valid method;
  • if not, return a null value.

foo['bar'] on the other hand only works with PHP arrays:

  • check if foo is an array and bar a valid element;
  • if not, return a null value.

If you want to access a dynamic attribute of a variable, use the attribute function instead.

Global Variables

The following variables are always available in templates:

  • _self: references the current template name;
  • _context: references the current context;
  • _charset: references the current charset.

Setting Variables

You can assign values to variables inside code blocks. Assignments use the set tag:

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

Filters

Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.

The following example removes all HTML tags from the name and title-cases it:

1
{{ name|striptags|title }}

Filters that accept arguments have parentheses around the arguments. This example will join a list by commas:

1
{{ list|join(', ') }}

To apply a filter on a section of code, wrap it in the filter tag:

1
2
3
{% filter upper %}
    This text becomes uppercase
{% endfilter %}

Go to the filters page to learn more about built-in filters.

Functions

Functions can be called to generate content. Functions are called by their name followed by parentheses (()) and may have arguments.

For instance, the range function returns a list containing an arithmetic progression of integers:

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

Go to the functions page to learn more about the built-in functions.

Named Arguments

1
2
3
{% for i in range(low=1, high=10, step=2) %}
    {{ i }},
{% endfor %}

Using named arguments makes your templates more explicit about the meaning of the values you pass as arguments:

1
2
3
4
5
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}

{# versus #}

{{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}

Named arguments also allow you to skip some arguments for which you don't want to change the default value:

1
2
3
4
5
{# the first argument is the date format, which defaults to the global date format if null is passed #}
{{ "now"|date(null, "Europe/Paris") }}

{# or skip the format value by using a named argument for the time zone #}
{{ "now"|date(timezone="Europe/Paris") }}

You can also use both positional and named arguments in one call, in which case positional arguments must always come before named arguments:

1
{{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}

Each function and filter documentation page has a section where the names of all arguments are listed when supported.

Control Structure

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elseif/else), for-loops, as well as things like blocks. Control structures appear inside {% ... %} blocks.

For example, to display a list of users provided in a variable called users, use the for tag:

1
2
3
4
5
6
<h1>Members</h1>
<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>

The if tag can be used to test an expression:

1
2
3
4
5
6
7
{% if users|length > 0 %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}

Go to the tags page to learn more about the built-in tags.

Comments

To comment-out part of a line in a template, use the comment syntax {# ... #}. This is useful for debugging or to add information for other template designers or yourself:

1
2
3
4
5
{# note: disabled template because we no longer use this
    {% for user in users %}
        ...
    {% endfor %}
#}

Including other Templates

The include function is useful to include a template and return the rendered content of that template into the current one:

1
{{ include('sidebar.html') }}

By default, included templates have access to the same context as the template which includes them. This means that any variable defined in the main template will be available in the included template too:

1
2
3
{% for box in boxes %}
    {{ include('render_box.html') }}
{% endfor %}

The included template render_box.html is able to access the box variable.

The name of the template depends on the template loader. For instance, the Twig_Loader_Filesystem allows you to access other templates by giving the filename. You can access templates in subdirectories with a slash:

1
{{ include('sections/articles/sidebar.html') }}

This behavior depends on the application embedding Twig.

Template Inheritance

The most powerful part of Twig is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.

Sounds complicated but it is very basic. It's easier to understand it by starting with an example.

Let's define a base template, base.html, which defines a simple HTML skeleton document that you might use for a simple two-column page:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!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>

In this example, the block tags define four blocks that child templates can fill in. All the block tag does is to tell the template engine that a child template may override those portions of the template.

A child template might look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{% 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 %}

The extends tag is the key here. It tells the template engine that this template "extends" another template. When the template system evaluates this template, first it locates the parent. The extends tag should be the first tag in the template.

Note that since the child template doesn't define the footer block, the value from the parent template is used instead.

It's possible to render the contents of the parent block by using the parent function. This gives back the results of the parent block:

1
2
3
4
5
{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ parent() }}
{% endblock %}

The documentation page for the extends tag describes more advanced features like block nesting, scope, dynamic inheritance, and conditional inheritance.

Twig also supports multiple inheritance with the so called horizontal reuse with the help of the use tag. This is an advanced feature hardly ever needed in regular templates.

HTML Escaping

When generating HTML from templates, there's always a risk that a variable will include characters that affect the resulting HTML. There are two approaches: manually escaping each variable or automatically escaping everything by default.

Twig supports both, automatic escaping is enabled by default.

The automatic escaping strategy can be configured via the autoescape option and defaults to html.

Working with Manual Escaping

If manual escaping is enabled, it is your responsibility to escape variables if needed. What to escape? Any variable you don't trust.

Escaping works by piping the variable through the escape or e filter:

1
{{ user.username|e }}

By default, the escape filter uses the html strategy, but depending on the escaping context, you might want to explicitly use any other available strategies:

1
2
3
4
{{ user.username|e('js') }}
{{ user.username|e('css') }}
{{ user.username|e('url') }}
{{ user.username|e('html_attr') }}

Working with Automatic Escaping

Whether automatic escaping is enabled or not, you can mark a section of a template to be escaped or not by using the autoescape tag:

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

By default, auto-escaping uses the html escaping strategy. If you output variables in other contexts, you need to explicitly escape them with the appropriate escaping strategy:

1
2
3
{% autoescape 'js' %}
    Everything will be automatically escaped in this block (using the JS strategy)
{% endautoescape %}

Escaping

It is sometimes desirable or even necessary to have Twig ignore parts it would otherwise handle as variables or blocks. For example if the default syntax is used and you want to use {{ as raw string in the template and not start a variable you have to use a trick.

The easiest way is to output the variable delimiter ({{) by using a variable expression:

1
{{ '{{' }}

For bigger sections it makes sense to mark a block verbatim.

Macros

Macros are comparable with functions in regular programming languages. They are useful to reuse often used HTML fragments to not repeat yourself.

A macro is defined via the macro tag. Here is a small example (subsequently called forms.html) of a macro that renders a form element:

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

Macros can be defined in any template, and need to be "imported" via the import tag before being used:

1
2
3
{% import "forms.html" as forms %}

<p>{{ forms.input('username') }}</p>

Alternatively, you can import individual macro names from a template into the current namespace via the from tag and optionally alias them:

1
2
3
4
5
6
7
8
{% 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>

A default value can also be defined for macro arguments when not provided in a macro call:

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

If extra positional arguments are passed to a macro call, they end up in the special varargs variable as a list of values.

Expressions

Twig allows expressions everywhere. These work very similar to regular PHP and even if you're not working with PHP you should feel comfortable with it.

The operator precedence is as follows, with the lowest-precedence operators listed first: b-andb-xorb-ororand==!=<>>=<=inmatchesstarts withends with..+-~*///%is**|[], and .:

1
2
3
4
5
6
7
{% set greeting = 'Hello ' %}
{% set name = 'Fabien' %}

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

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

Literals

The simplest form of expressions are literals. Literals are representations for PHP types such as strings, numbers, and arrays. The following literals exist:

  • "Hello World": Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (for example as arguments to function calls, filters or just to extend or include a template). A string can contain a delimiter if it is preceded by a backslash (\) -- like in 'It\'s good'. If the string contains a backslash (e.g. 'c:\Program Files') escape it by doubling it (e.g. 'c:\\Program Files').

  • 42 / 42.23: Integers and floating point numbers are created by just writing the number down. If a dot is present the number is a float, otherwise an integer.

  • ["foo", "bar"]: Arrays are defined by a sequence of expressions separated by a comma (,) and wrapped with squared brackets ([]).

  • {"foo": "bar"}: Hashes are defined by a list of keys and values separated by a comma (,) and wrapped with curly braces ({}):

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    {# keys as string #}
    { 'foo': 'foo', 'bar': 'bar' }
    
    {# keys as names (equivalent to the previous hash) #}
    { foo: 'foo', bar: 'bar' }
    
    {# keys as integer #}
    { 2: 'foo', 4: 'bar' }
    
    {# keys as expressions (the expression must be enclosed into parentheses) #}
    {% set foo = 'foo' %}
    { (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' }
    
  • true / falsetrue represents the true value, false represents the false value.

  • nullnull represents no specific value. This is the value returned when a variable does not exist. none is an alias for null.

Arrays and hashes can be nested:

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

Using double-quoted or single-quoted strings has no impact on performance but string interpolation is only supported in double-quoted strings.

Math

Twig allows you to calculate with values. This is rarely useful in templates but exists for completeness' sake. The following operators are supported:

  • +: Adds two objects together (the operands are casted to numbers). {{ 1 + 1 }} is 2.
  • -: Subtracts the second number from the first one. {{ 3 - 2 }} is 1.
  • /: Divides two numbers. The returned value will be a floating point number. {{ 1 / 2 }} is {{ 0.5 }}.
  • %: Calculates the remainder of an integer division. {{ 11 % 7 }} is 4.
  • //: Divides two numbers and returns the floored integer result. {{ 20 // 7 }} is 2{{ -20 // 7 }} is -3 (this is just syntactic sugar for the round filter).
  • *: Multiplies the left operand with the right one. {{ 2 * 2 }} would return 4.
  • **: Raises the left operand to the power of the right operand. {{ 2 ** 3 }} would return 8.

Logic

You can combine multiple expressions with the following operators:

  • and: Returns true if the left and the right operands are both true.
  • or: Returns true if the left or the right operand is true.
  • not: Negates a statement.
  • (expr): Groups an expression.

Twig also support bitwise operators (b-andb-xor, and b-or).

Operators are case sensitive.

Comparisons

The following comparison operators are supported in any expression: ==!=<>>=, and <=.

You can also check if a string starts with or ends with another string:

1
2
3
4
5
{% if 'Fabien' starts with 'F' %}
{% endif %}

{% if 'Fabien' ends with 'n' %}
{% endif %}

For complex string comparisons, the matches operator allows you to use regular expressions:

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

Containment Operator

The in operator performs containment test.

It returns true if the left operand is contained in the right:

1
2
3
4
5
{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

You can use this filter to perform a containment test on strings, arrays, or objects implementing the Traversable interface.

To perform a negative test, use the not in operator:

1
2
3
4
{% if 1 not in [1, 2, 3] %}

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

Test Operator

The is operator performs tests. Tests can be used to test a variable against a common expression. The right operand is name of the test:

1
2
3
{# find out if a variable is odd #}

{{ name is odd }}

Tests can accept arguments too:

1
{% if post.status is constant('Post::PUBLISHED') %}

Tests can be negated by using the is not operator:

1
2
3
4
{% if post.status is not constant('Post::PUBLISHED') %}

{# is equivalent to #}
{% if not (post.status is constant('Post::PUBLISHED')) %}

Go to the tests page to learn more about the built-in tests.

Other Operators

The following operators don't fit into any of the other categories:

  • |: Applies a filter.

  • ..: Creates a sequence based on the operand before and after the operator (this is just syntactic sugar for the range function):

    1
    2
    3
    4
    {{ 1..5 }}
    
    {# equivalent to #}
    {{ range(1, 5) }}
    

    Note that you must use parentheses when combining it with the filter operator due to the operator precedence rules:

    1
    (1..5)|join(', ')
    
  • ~: Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is 'John'Hello John!.

  • .[]: Gets an attribute of an object.

  • ?:: The ternary operator:

    1
    2
    3
    {{ foo ? 'yes' : 'no' }}
    {{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
    {{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
    
  • ??: The null-coalescing operator:

    1
    2
    {# returns the value of foo if it is defined and not null, 'no' otherwise #}
    {{ foo ?? 'no' }}
    

String Interpolation

String interpolation (#{expression}) allows any valid expression to appear within a double-quoted string. The result of evaluating that expression is inserted into the string:

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

Whitespace Control

The first newline after a template tag is removed automatically (like in PHP.) Whitespace is not further modified by the template engine, so each whitespace (spaces, tabs, newlines etc.) is returned unchanged.

Use the spaceless tag to remove whitespace between HTML tags:

1
2
3
4
5
6
7
{% spaceless %}
    <div>
        <strong>foo bar</strong>
    </div>
{% endspaceless %}

{# output will be <div><strong>foo bar</strong></div> #}

In addition to the spaceless tag you can also control whitespace on a per tag level. By using the whitespace control modifier on your tags, you can trim leading and or trailing whitespace:

1
2
3
4
5
6
7
{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
    {{- value -}}
{%- endif -%}

{# output 'no spaces' #}

The above sample shows the default whitespace control modifier, and how you can use it to remove whitespace around tags. Trimming space will consume all whitespace for that side of the tag. It is possible to use whitespace trimming on one side of a tag:

1
2
3
4
{% set value = 'no spaces' %}
<li>    {{- value }}    </li>

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

Extensions

Twig can be easily extended.

If you are looking for new tags, filters, or functions, have a look at the Twig official extension repository.

If you want to create your own, read the Creating an Extension chapter.

« Installation Twig for Developers »

 

 

猜你喜欢

转载自blog.csdn.net/sinat_15955423/article/details/81236499