Twig for template designers (under)-twig User Guide

Source: Internet
Author: User
Tags bitwise operators

Original address: http://my.oschina.net/veekit/blog/276800

12. Template Inheritance

The most powerful part of twig is template inheritance. Template inheritance allows you to create a basic "skeleton" template that contains all the common elements of your site, and defines some chunks (blocks) that allow child templates to be overwritten.

Sounds complicated, but in fact it's very basic. It is easy to understand through an example.

Let's define a basic template: base.html. It defines a simple HTML framework document, assuming that you want to use a simple two-column distributed page:

<! DOCTYPE html><body>        <div id= "content" >{% block content%}{% endblock%}</div> <div        id= "Footer" >            {% block footer%}                ©copyright by <a href= "Http://domain.invalid/" >YOU</A>.            {% Endblock%}        </div>    </body>

  

In this example, the block tag defines four chunks (blocks) that allow the child template to be populated. The purpose of all blcok tags is to tell the template engine that a child template may overwrite those parts of the template (that is, it will overwrite chunks).

A child template might look like this:

{% extends "base.html"%} {% block title%}  index{% endblock%}{% block head%}    {{parent ()}}    <style type= "Text/css" >        . Important {color: #336699; }    </style>{% endblock%}{% block content%}    

  

The extension tag (extends) is the key here. It tells the template engine that this template extends to another template. When the template system evaluates this template, it first finds the parent of the current stencil. The extension label (extends) must be the first label in the template.

Note that because the child template does not have a footer chunk defined, the values in the parent template will be used instead.

Renders the contents of the parent chunk by using the parent function. This allows you to return the result of the parent chunk:

{% block sidebar%}    

  

Tip 1: The extended tags (extends) documentation page describes more advanced features such as block nesting, scope of application, dynamic inheritance, and conditional inheritance.

Tip 2: With the help of the use tag, multiple inheritance is also supported through the so-called horizontal reuse twig. This is an advanced feature that rarely needs to be used by regular templates.

HTML escape

When generating HTML from a template, there is always a risk that a variable will contain some characters that affect the final HTML. There are two ways to solve this problem: manually escaping each variable or automatically escaping everything by default. Both methods are supported by Twig, and auto-escaping is enabled by default.

Tip: The Escaper extension is enabled (by default), and automatic escaping is only valid.

13.1 Working with manual escape

If manual escape is enabled, the escape variable is your responsibility, if you need to. What do I need to escape? Any variables that you do not trust.

The escape function escapes the variable via escape or E filter:

{{User.username|e}}

The escape filter uses the HTML policy by default, but depending on the escaped context, you might want to explicitly use any of the other available policies:

{{user.username|e (' JS ')}} {{user.username|e (' CSS ')}} {{user.username|e (' URL ')}} {{user.username|e (' html_attr ')}}

  

13.2 Working with automatic escape

Whether auto-escape is enabled or not, you can use the Autoescape tag to mark part of a template as escaped or not escaped:

{% Autoescape%}    Everything'll be automatically escaped in this block (using the HTML strategy) {% Endautoescape%}

By default, policies that use HTML escaping are automatically escaped. If you output variables in other situations, you need to explicitly escape them with the appropriate escape policy:

{% autoescape ' js '%}    Everything'll be automatically escaped in this block (using the JS strategy) {% Endautoescape%}

  

13.3 Escaping

Sometimes it is desirable or necessary for twig to ignore other processing as a variable or chunk (block). For example, if you use the default syntax and want to use {{{} as a string in the original template instead of using a variable delimiter, you must use a trick.

The simplest method is to output the delimiter of a variable by using a variable expression ({):

{{ ‘{{‘ }}

For larger portions, tagging with verbatim tags is meaningful.

14. Macro (Macros)

Tip: Version 1.12 new features: Added support for default parameter values in Twig 1.12.

Macros are features that can be comparable to conventional programming languages. They are useful for reusing commonly used HTML fragments without having to constantly repeat themselves. Macros are defined by macro tags. Here is an example of a form element that is rendered by a macro (called forms.html):

{% macro input (name, value, type, size)%}    <input type= "{{type|default (' text ')}}" Name= "{{name}}" Value= "{{value|e}}" Size= "{{size|default}}"/>{% Endmacro%}

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

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

Alternatively, you can import individual macro names from one template to the current template by using the From tab, and optionally use aliases to name them:

{% 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>

When a macro is called, the default value is defined if no macro parameters are provided:

{% macro input (name, value = "", type = "Text", size = +)%}    <input type= "{{type}}" Name= "{{name}}" Value= "{{value|e}}" size= "{{size}}"/>{% Endmacro%}

  

15. Expressions

Twig allows expressions to be used everywhere. This is very similar to regular PHP, and even if you don't use PHP, you'll feel comfortable.

Tip: The operator takes precedence as follows, which first lists the lowest-priority operations:

  

{% Set greeting = ' Hello '%} {% Set name = ' Fabien '%} {{Greeting ~ name|lower}}   {# Hello Fabien #} {# Use parenthesis to change precedence #} {{(greeting ~ name) |lower}} {# Hello Fabien #}

  

15.1 text

Tip: The new feature in version 1.5: Twig 1.5 adds support for the hash key as a name and an expression.

The simplest form of an expression is text. Text is represented in PHP types, such as strings, numbers, and arrays. The following text exists:

"Hello World": anything between two double quotes or single quotes is a string. They are useful when you need a string in a template (for example, a function call parameter, a filter, or just an extension or a template). A string can contain a delimiter if it is preceded by a backslash (\), for example: ' it\ ' good '. 42/42.23: Integers and floating-point numbers are created by a number that has just been written. If a number has a point, it is a floating point, otherwise it is an integer. ["foo", "Bar"]: An array is defined as a sequence of expressions separated by commas (,) and wrapped in square brackets ([]). {"foo": "Bar"}: the hash table is defined as a list of [keys] and [values] separated by commas (,), enclosed by curly braces ({}).

  

{# Keys As String #} {' foo ': ' foo ', ' Bar ': ' Bar '} {# keys as the name (equivalent to the previous hash table)--As of Twig 1.5 #} {foo: ' foo ', bar: ' Bar '} {# keys As Integer #} {2: ' foo ', 4: ' Bar '} {# keys as an expression (the expression must be wrapped in parentheses)--As of Twig 1.5 #} {(1 + 1): ' foo ', (a ~ ' B '): ' Bar '}

  

True/false:true represents a value of true and False indicates a false value. Null:null indicates that there are no specific values. This is the value returned when a variable does not exist. None is an alias of NULL.

Arrays and hashes can be nested:

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

Tip: Using double or single quote strings has no effect on performance, but only supports the insertion of variable values in double-quoted strings.

15.2 calculation

Twig allows you to calculate the value. Although rarely useful in a template, it exists for completeness. The following operators are supported:

+: Adds two objects together (the operand is cast to a number). {{}}} is 2. -  : Subtract the second number from the first number. {{3-2}} is 1. /: Divide two numbers. The returned value will be a floating-point number. {{1/2}} is {{0.5}}. %: Calculates the remainder of an integer being removed. {{11%7}} is 4. : The integer result that divides two numbers and returns the rounded down. {{20//7}} is 2,{{-20//7}} is-3 (this is just the syntax modification of the round filter). *: The left operand is multiplied by the right operation number. {{2*2}} will return 4. * *: power to the right operand (m) of the left operand (n). (That is, the M-time of N, n^m) {{2 * * 3}} will return 8.

  

15.3 logic

You can use the following operators for multiple expressions:

And: Returns True if both the left and right operands are true. Or: Returns true if the operand to the left or right is true. Not: Negates a declaration. (expr): forms a set of expressions.

Tip: Twig also supports bitwise operators (B-and, B-xor, and B-or).

15.4 comparison

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

You can also check whether a string begins or ends with another string:

{% 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:

{% If phone matches ' {^[\d\.] +$} '%}{% endif%}

  

15.5 include operator

In operator to include tests. Returns true if the left operand is contained in the left operand:

{# returns True #} {{1 in [1, 2, 3]}} {{' cd ' in ' ABCDE '}}

  

Tip: You can use this filter to include tests on strings, arrays, or objects that implement the Traversable interface.

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

{% if 1 not in [1, 2, 3]%} {# The above equals the following #} {% if not (1 in [1, 2, 3])%}

  

15.6 Test Operators

The IS operator can be tested. Tests can be used to test variables against a common expression. The right operand is the name of the test:

{# Find the variable that is odd #} {{name is odd}}

Tests can also accept parameters:

{% If Post.status is constant (' Post::P ublished ')%}

By using the is not operator, the test can be negated:

{% If post.status is not constant (' Post::P ublished ')%} {# The above equals the following #} {% if not (Post.status is constant (' Post::P ublished '))%}

Visit the tests page to learn more about built-in testing.

15.7 Other operators

Tip: 1.12. Version 0 new features: Twig 1.12.0 added support for extended ternary operators.

The following operators are useful, but do not belong to any other category:

.. : Creates a sequence based on the previous operand and the post operand (this is just the syntax decoration of the range function). | : Apply a filter. ~: All operands are converted to strings and joined together. {"Hello" ~ Name ~ "!"}} will return (assuming the name is ' John ') Hello John!.. , []: Gets the properties of an object. :  : Ternary operator (?:).

  

{{foo?} ' Yes ': ' No '}}{# as of Twig 1.12.0 #}{{foo?: ' No '} is the same as {{foo? foo: ' No '}}{{foo? ' Yes '} is the same as {foo? ' Yes ': '}}

  

15.8 string interpolation

Tip: New in version 1.5: string interpolation is added to the Twig 1.5 version.

string interpolation (#{expression}) allows any valid expression to appear in a double-quote wrapped string. In the result of the run, the expression is inserted into the string:

{"Foo #{bar} Baz"}} {"Foo #{1 + 2} Baz"}}

  

16. Blank character Control

Tip: New in version 1.1: The flag level whitespace control is added to the Twig 1.1 version.

The first line break after the template tag is automatically removed (as in PHP). Other whitespace characters are no longer modified by the template engine, so each whitespace (space, tab, line break, etc.) will be returned intact (to view).

Use the spaceless tag to remove the whitespace between HTML tags:

{% spaceless%}    <div>        <strong>foo bar</strong>    </div>{% endspaceless%}{# output will be:<div>< Strong>foo bar</strong></div> #}

In addition, for spaceless tags, you can also control white space characters at each label level. You can remove leading or trailing whitespace by using the white space character control modifier on your label:

{% Set value = ' no spaces '%} {#-has no leading or trailing white space characters-#} {%-If True-%}    {{-Value-}} {%-endif-%} {# output: ' No spaces ' #}

In the example above, the default whitespace control modifier is shown, and how to use it to remove whitespace around the label. However, by default, all whitespace characters on both sides of the label are removed. In fact, you can also use it only to remove whitespace from the label side:

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

  

17. Expansion

Twig can easily be extended. If you are looking for new tags, filters, or functions, you should look at the Twig official extension library.

End-of-article language:

Because the latest is too busy, resulting in the distance from the first translation is now over more than 10 genius translated the article. It's really not easy. Hopefully this article will give you a real help with the readers you need to use. Please specify the source and link of the original. Thank you!

Original address: http://my.oschina.net/veekit/blog/276800

Twig for template designers (under)-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.