Getting Started with Twig template language

Source: Internet
Author: User
Tags iterable

Transferred from: http://pengbotao.cn/twig-template-language.html

There are two types of delimiters in twig {% ...%} and {{...}}, which is used to execute statements such as for loops, if judgments, filters, etc., which are used to display variables in the latter template.

Twig common usage

Available symbols

= = = < > >= <= +-~ *///% * | [] . .. And or not in is B-and b-or B-xor
The meanings of some symbols are as follows

~: Connect two strings, equivalent to a dot in PHP
//: Divisible
* *: exponentiation, equivalent to ^ in PHP
B-and, B-or, B-xor: Bitwise AND, bitwise OR, Bitwise XOR
-: Subtraction and shorthand usage for removing whitespace, such as {{-data}} = Remove Left blank, {{data-}} = Remove blank on right, {{-data-}} = Remove blank on both sides

Comments

{# This is Twig Comment #}

Variable

Foo is a PHP assignment variable, you can use {{foo}} in the template
If the variable is an array or an object, you can use {{Foo.bar}} to represent it, or you can call a method in the class directly, such as {{foo.getname}} or use {{Foo.getname (P1, p2, p3)} When arguments are passed.

When {{Foo.bar}} is used in a template, PHP makes the following judgments to detect the value of the corresponding variable:
1. Detects if Foo is an array, and bar is a valid key
2. If Foo is an object, detects if bar is a valid property
3. If Foo is an object, but bar is not a valid property, the bar is detected as a valid method
4. If Foo is an object, but bar is not a valid method, then detecting if Getbar is a valid method
5. If Foo is an object, but Getbar is not a valid method, then detecting whether Isbar is a valid method
6. If not, returns null

When Foo is an array, the template can also be used this way: {{foo[' bar '}}

The variable does not define a default value setting:
{{Var|default (' var is not defined ')}}

You can declare a variable by using the {% Set variable name = variable value%}, or you can write {% set variable name%} variable value {% Endset%}

The non-associative array in PHP is mapped to [element 1, Element 2, ...], and the associative array is mapped to {Key 1: value 1, key 2: Value 2, ...}

Array traversal

--Iterate by array value:

123 {% forvalue in foo %}    {{ value }}{% endfor%}

--Iterate by the array key:

123 {% forkey in foo|keys %}    {{ key }}{% endfor%}

--Press Key,value to traverse

123 {% forkey, value in foo %}    {{ key}}:{{value }}{% endfor%}

--if Foo is not an array, you can also use the Else statement, such as:

12345 {% forkey, value in foo %}    {{ key}}:{{value }}{% else %}      foo is Not a Array{% endfor%}

--can also be directly with the condition, traversing the two-dimensional array is useful, can be used Value.field to judge:

123 {% forkey, value in foo if value == 1%}    {{ key}}:{{value }}{% endfor%}

Internal variables of the loop body:
Number of Loop.index cycles (starting from 1)
Number of loop.index0 cycles (starting from 0)
loop.revindex Number of cycles left (minimum value 1)
loop.revindex0 Number of cycles left (minimum value 0)
Loop.first Returns True when the first loop
loop.last Returns True when the last loop occurs
Total number of loop.length loops
loop.parent array to be looped

Conditional statements

--need to use or and and instead of | |, &&

123 {% ifa == ‘1‘ or b == ‘2‘ %}a = 1 or b = 2{% endif%}

--Determining whether a variable is defined

123 {% ifvar is not defined %}    {# do something #}{% endif%}

--Is NULL

123 {% ifvar is null %}    {# do something #}{% endif%}

--Is False

123 {% ifvar is sameas(false) %}    {# do something %}{% endif%}
Parsing delimiters
123456789 {{ ‘{{‘}} {% raw %}    <ul>    {% for item in seq %}        <li>{{ item }}</li>    {% endfor%}    </ul>{% endraw %}
Control structure

{% if AAA%} XXX {% ElseIf bbb%} yyy {% Else%}ZZZ: Judgment statement
{% for%} XXX {% endfor%}: Iteration Variables
{% do%}: No other meaning, {% do 1+2%} equals {{1+2}}
{% flush%}: Refreshes the output buffer, equivalent to flush
{% include%}: Include template
{% extends%}: Extending Templates
{% embed%} XXX {% endembed%}: Contains the template and extends the content of the template, which is equivalent to the inclusion and extends
{% use%}: include template, approximate to multiple inheritance
{% from AAA import BBB as CCC%}: Import macros from the specified template and set aliases
{% macro%} XXX {% Endmacro%}: Defines a macro for multiple calls, as in defining PHP functions
{% sandbox%} {% include xxx%} {% Endsandbox%}: Specifies sandbox mode for imported templates, only valid for include statements, only if sandbox mode is turned on
{% block xxx%} or {% block%} XXX {% endblock% }: Define code blocks or overwrite code blocks
{% set xxx%} or {% set%} XXX {% endset%}: Defining variables within a template
{% filter%} XXX {% endfilter%}: Multi-line Filter
{% spaceless%} XXX {% endspaceless%}: Remove spaces from HTML fragments
{% autoescape%} XXX {% endautoescape%}: The string is securely processed into a valid specified data
{% verbatim%} XXX {% endverbatim%}: Block the compilation of the template engine, which is the new name of raw

Built-in filter

Filters are used to modify the data, and each filter can be separated by a vertical bar for chained calls, with parentheses passing parameters

The filter can also be used as a separate function, in the following form:

123 {% filter Name%} data to be processed {% Endfilter%}

Batch: splits the array into smaller arrays by the specified number, and the second optional parameter is used to populate with insufficient elements. such as {{[1, 2, 3, 4, 5]|batch (2, ' Noitem ')}} = [[1, 2], [3, 4], [5, ' Noitem ']
date_modify: modification time, often associated with date. such as {{' |date_modify (' +3 days ') |date (' y-m-d ')}} = Displays the current time plus 3 day
Default : provides defaults when the decorated data does not exist or is empty. As {{' |default (' Ruchee ')}} = ' Ruchee '
Escape: The string is safely processed into a valid specified data, abbreviated to E, supports a variety of conversion modes, the default mode is HTML, and other optional modes are html_attr, JS, CSS, URL
First : returns the first character of the array, or a string. such as {{{a:1, b:2, C:3}|first}} = 1
Last : returns the last character of the array, or string. such as {{{a:1, b:2, c:3}|last}} = 3
Replace : replaces the specified content in a string. such as {'% '% love%s2 ' |replace ({'% ": ' Ruchee ', '%s2 ': ' Vim '}}}} = ' Ruchee love Vim '
Raw: Let the data fail in the Autoescape filter

A filter borrowed from PHP's own function

ABS:Take absolute value
NL2BR:Replace \ n in string with <br/>
Join:Composes the individual elements of an array into a string by a specified delimiter
Sort:Sort an array
Trim:Removes the specified character from the end of the string, and the default is a space
Date:Format time, which can handle strtotime-compatible strings, or instances of Datetime/dateinterval, the optional second parameter is used to specify the time zone, and if the decorated data is empty it defaults to the current time
Reverse:Reverses an array or string, adding the processing of the string to the base of the Array_reverse
Slice:Intercepts an array or part of a string, adding a string to the Array_slice base
Keys:Extracts all the key names of an array into an array, equivalent to Array_keys
Merge:Merges two arrays, similar to Array_merge. such as {{array 1|merge (array 2)}}
Length:Returns the number of array elements or the length of a string, equivalent to the combination of count and strlen
Capitalize:Capitalize the first letter of a string, equivalent to Ucfirst
Title:Capitalize the first letter of each word in a string, equivalent to Ucwords
Lower:Converts all letters of a string into lowercase, equivalent to Strtolower
Upper:All letters of the string are capitalized, equivalent to Strtoupper
Split:Splits a string into an array, equivalent to Str_split
Striptags:Removes the html/php tag from the string, equivalent to Strip_tags
Url_encode:Encoded link string, equivalent to UrlEncode
Json_encode:Encoded JSON format, equivalent to Json_encode
format:Formats a string, similar to printf. such as {{' My name is%s, and I love%s ' |format (' Ruchee ', ' Vim ')}} = ' My name is Ruchee, and I love Vim '
Number_format:Formatted value, equivalent to Number_format
convert_encoding:Encoding conversion, the first parameter specifies the converted encoding, the second parameter specifies the encoding before the conversion, approximately iconv

Built-in functions

even: is even
odd: is odd
empty: is empty
null: is null
defined: defined
sameas: The target variable and the specified value point to the same address in memory, using the form if Variable value is sameas (specified value)
Divisibleby: The target value can be divisible by the specified values, using the form if target numeric value Divisibleby (specified value), where the specified value cannot be 0
iterable: Whether the target variable is an array or whether it can be iterated, using the form if variable value is iterable
attribute: dynamically gets the value of the variable property, two forms of use are Attribute (array, ' element name ') and attribute (object, ' method name ', optional parameter)
BLOCK: repeatedly references the specified code block, such as {{block (' title ')}}
constant: take a constant value from a string or object
cycle: loop displays an array of elements, called cycle (array, a loop variable)
Date: format time
Dump: Displays detailed variable information when debugging mode is turned on, equivalent to Var_dump
include: Contains additional template files
parent: used to refer to the contents of the parent fragment when overwriting a code snippet
random: manufacturing a random number
range: The returns an array of a specified interval, specifying the step size, Twig use: As a simple usage, equivalent to range
template_from_string: load template based on string

Getting started with twig template language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.