Twig for template designers (UP)-twig User Guide

Source: Internet
Author: User

1. Overview

The template is a simple text file. It can generate any text-based format (HTML, XML, CSV, and so on). It does not have a specific extension, HTML or XML is OK. A variable or expression contained in a template that controls the logic of a template. When templates are preprocessed, they are replaced with variable values.

The following is a minimal template that illustrates some of the basic elements. We'll cover more details later:

<! DOCTYPE html>

  

Twig has two types of separators: {% ... %} and {{...}}. The first is a control statement that executes such as a For loop, which prints the result of an expression in the template.

2. IDEs Integration

Many IDES support twig syntax highlighting and auto-completion tags:

※textmate via Twig Bundle

※vim via Jinja Syntax plugin or Vim-twig plugin

※netbeans via Twig Syntax plug-in (7.2+)

※phpstorm (native 2.1+)

※eclipse through Twig plugin

※sublime via Twig Bundle

※gtksourceview through Twig language definition

※coda and SubEthaEdit via Twig syntax mode

※coda 2 via other Twig syntax mode

※komodo and Komodo Edit via Twig highlight/syntax check mode

※notepad++ through notepad++ Twig highlighter

※emacs through Web-mode.el

3. Variables

The application passes the variable to the template of the operation. You can also access the properties or elements of a variable. The visual representation of a variable depends to a large extent on the value provided by the application. You can use the dot (.) Or the so-called Under-Banner method ([]) to access the properties of a variable (PHP object's method or property, the elements of the PHP array).

{{Foo.bar}} {{foo[' bar '}}

When the attribute contains special characters (such as-this is interpreted as the minus operator), use the attribute () function instead of the point of Use (.). To access variable properties:

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

Important: Be aware that curly braces are not part of a variable, except for print statements. When accessing variables within a tag, do not add braces to the variable.

If a variable or property does not exist, you will receive a null value when the Strict_variables option is set to False, and an error will be thrown if Strict_variables is set to True,twig (see environment Options

Variable invocation mechanism

For the sake of convenience, when invoking foo.bar in the PHP presentation layer, the following actions are performed:

A.1 checks if Foo is an array and checks if bar is a valid element A.2 if not, Foo is an object and checks if bar is a valid property a.3 if not, Foo is an object and checks if bar is a valid method. (Even if bar is a constructor.) Then use the __construct () method instead of A.4 if it is not, Foo is an object that checks whether Getbar () is a valid method a.5 if not, Foo is an object that checks whether Isbar () is a valid method a.6 if not, returns a null value (NULL) A.7 Check foo is an array and bar is a valid element; A.8 if not, a null value is returned.

4. Global variables

The following variables are always available in the template:

_self: referencing the current template;

_context: Refers to the current context;

_charset: Refers to the current character set.

5. Setting variables

You can assign a value to a variable in an internal code block. Assigning values using the SET tag:

{% Set foo = ' foo '%} {% Set foo = [1, 2]%} {% Set foo = {' foo ': ' Bar '}%}

  

6. Filter

Variables can be modified through the filter. Use pipe symbols (i.e. vertical bars |) between filters and variables Separated, there may be optional parameters in the filter brackets. Multiple filters can be used in a concatenation, and the output of the filter is applied to the next filter.

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

{{Name|striptags|title}}

The filter accepts the arguments in parentheses. This example will concatenate a list with commas:

{{List|join (', ')}}

To apply a filter to a piece of code, simply wrap it up with the filter tag:

{% filter upper%}    This text becomes uppercase{% endfilter%}

  

Visit the Filters page to learn more about the built-in filters.

7. Functions

Functions can be called to generate content. Functions are called through their [function name + ()] and may also have parameters.

For example, the range () function returns a list that contains an integer arithmetic progression:

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

  

Visit the Functions page to learn more about built-in functions.

8. Named parameters

1.12 New features: support for named parameters is added to twig version 1.12.

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

Use named parameters to give your template a clearer understanding of the meaning of the values you pass as parameters:

{{data|convert_encoding (' UTF-8 ', ' ISO-2022-JP ')}} {# versus (contrast) #} {{data|convert_encoding (from= ' iso-2022-jp ', to= ' UTF-8 ')}}

Named parameters also allow you to skip some parameters that you do not want to change the default values for:

{# 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 placeholder parameters and named parameters in a call, in which case the placeholder parameter must precede the named parameter:

{"Now" |date (' d/m/y h:i ', timezone= "Europe/paris")}}

  

Tip: Each function and filter's document page has a section that lists all of the parameter names that they support.

9. Control structure

A control structure refers to the code for all of these control procedures: conditional statements (such as: If/elseif/else), for loops, and similar blocks of code. Control structure appears in {% ... %} within the block.

For example, to display a list of users provided by the variable (users), use the for label:

The IF tag can be used to test an expression:

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

Visit the tags page to learn more about the built-in labels.

10. Notes

To comment out a portion of the template, use the comment syntax {#...#}. This is useful for debugging or adding information to other template designers or for your own viewing:

{# note:disabled template because we no longer    use this {% for user in users%}        ...    {% ENDfor%}#}

  

11. Include Other templates

When you include a template, the include tag is useful, and it returns the contents of the template (the child templates) to the current stencil (parent template):

{% include ' sidebar.html '%}

By default, each contained template is passed the current context. The context passed to the parent template and also includes variables defined in the child template:

{% for box in boxes%}    {% include "render_box.html"%} {% ENDFOR%}

  

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

The file name of the template depends on the template loader. For example, Twig_loader_filesystem allows you to access other templates by giving them a file name. You can access the templates in the sub-directories separated by a slash:

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

This behavior depends on embedding twig in the application.

Twig for template designers (UP)-twig User Guide

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.