TWIG Template Design Quick Start manual Chinese _php tutorial

Source: Internet
Author: User
Tags sublime text
Wrote a few things about twig. I haven't written a quick start or something like that. Just write it now.

Profile
Twig templates are normal text files and do not require a special extension,. html. htm. Twig can be.
Variables and expressions within the template are parsed and replaced at run time, and tags will control the logic of the template
Here is the smallest template to illustrate some basic things




My webpage



      {% for item in navigation%}
    • {{Item.caption}}

    • {% ENDFOR%}


My webpage


{{a_variable}}





<title>My webpage</title>



      {% for item in navigation%}
    • {{Item.caption}}

    • {% ENDFOR%}

My webpage


{{a_variable}}


It contains two symbols {% ...%} and {{...}} The first to control such as a for loop or something, and the second is to output variables and expressions.


IDE Support
Many Ides highlight support for Twig. Everybody find what they need.
TextMate via the Twig bundle
Vim via the Jinja syntax plugin
Netbeans via the Twig syntax plugin
Phpstorm (native as of 2.1)
Eclipse via the Twig plugin
Sublime Text via the Twig bundle
Gtksourceview via the Twig language definition (used by gedit and other projects)
Coda and SubEthaEdit via the Twig syntax mode
Variable
The program will pass to the template several variables, you need to output them in the template. such as output $hello

{{Hello}}
{{Hello}} if the object or array is passed to the template, you can use the dot. To output the properties or methods of an object, or the members of an array. Or you can use the subscript method.
{{Foo.bar}}
{{foo[' bar '}}
{{Foo.bar}}
{{foo[' bar '}}
If the value you access does not exist, it will return null. Twig has a complete set of processes to confirm the existence of a value.


For.bar will do the following:
。。。 If Foo is an array, try to return to the bar member and, if it does not exist, continue down
。。。 If Foo is an object, it will attempt to return the Bar property, and if it does not, proceed down
。。。 Will attempt to run the bar method, and if it does not exist, proceed down
。。。 Will attempt to run the Getbar method, and if it does not exist, proceed down
。。。 Tries to run the Isbar method and returns null if it does not exist


for[' Bar ' is a lot easier. For must be a number of arrays, try to return a bar member, if not return null
Global variables
Twig defines some global variables.

_self this see macro label
_context This is the current environment.
_charset: The current character encoding


Assigning values to variables
See Set label for details

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


Filter Firters
Variables can be modified by filters. Filters and variables are separated by (|). Filters can also have parameters. Filters can also be used in multiple uses.
The following example uses two filters.

{{Name|striptags|title}}
{{Name|striptags|title}}striptas represents the removal of the HTML tag, title indicates the first letter of each word capitalized. More filters See my Blog


Filters can also be used in code blocks, see filter tags

{% Filter Upper%}
This text becomes uppercase
{% endfilter%}
{% Filter Upper%}
This text becomes uppercase
{% endfilter%}

Functional function
This is nothing to say, will write the program know, Twig built up some functions, refer to my Blog
For example, to return an array of 0 to 3, use the range function
{% for I in range (0, 3)%}
{{i}},
{% ENDFOR%}
{% for I in range (0, 3)%}
{{i}},
{% ENDFOR%}

Process Control
Supports for loop and if/elseif/else structures. Just look at the example, there's nothing to say.

Members



      {% for user in users%}
    • {{User.username|e}}

    • {% ENDFOR%}

Members



      {% for user in users%}
    • {{User.username|e}}

    • {% ENDFOR%}

{% if users|length > 0}

      {% for user in users%}
    • {{User.username|e}}

    • {% ENDFOR%}

{% ENDIF%}
{% if users|length > 0}

      {% for user in users%}
    • {{User.username|e}}

    • {% ENDFOR%}

{% ENDIF%}


Comments
The contents of {# ... #} are commented out and can be a single line or multiple lines.


Loading additional templates
See the Include tag (translated in my blog) and return the rendered content to the current template

{% include ' sidebar.html '%}
{% include ' sidebar.html '%} The variables of the current template are also passed to the include template, where you can directly access the variables of your template.
Like what

{% for box in boxes%}
{% include "render_box.html"%}
{% ENDFOR%}
{% for box in boxes%}
{% include "render_box.html"%}
{% endfor%} in render_box.html is an access to the box variable
Adding additional parameters allows the loaded template to access only a subset of the variables, or to be completely inaccessible. Reference Manuals


Template inheritance
The most useful feature in Twig is template inheritance, which allows you to create a "skeleton template" and then you can override any part of the parent template with a different block. And it's very easy to use.
Let's define a basic skeleton page base.html He contains many block blocks that can be covered by the quilt template.




{% block head%}

<title>{% block title%} {% Endblock%}-My webpage</title>
{% Endblock%}


{% block content%} {% Endblock%}

{% block footer%}
©copyright by.
{% Endblock%}






{% block head%}

<title>{% block title%} {% Endblock%}-My webpage</title>
{% Endblock%}


{% block content%} {% Endblock%}

{% block footer%}
©copyright by.
{% Endblock%}


We have defined 4 block blocks, namely Block head, block title, block content, block footer
Attention
1, block can be nested.
2, block can set the default value (the contents of the middle), if the sub-template is not covered, then the default value is displayed directly. For example, block footer, most of the pages you do not need to change (effort), but you need to still be able to modify (flexible)
Below I see how the template should be defined.
{% extends "base.html"%}

{% block title%} index{% Endblock%}
{% block head%}
{{parent ()}}

{% Endblock%}
{% block content%}

Index



Welcome on my awesome homepage.


{% Endblock%}
{% extends "base.html"%}

{% block title%} index{% Endblock%}
{% block head%}
{{parent ()}}

{% Endblock%}
{% block content%}

Index



Welcome on my awesome homepage.


{% Endblock%} Note {% extends "base.html"%} must be the first label. The block footer is not defined, so the default values set in the parent template are displayed
If you need to add a block of content instead of full coverage, you can use the parent function

{% block sidebar%}

Table of Contents


...
{{parent ()}}
{% Endblock%}
{% block sidebar%}

Table of Contents


...
{{parent ()}}
{% Endblock%}
Extends tags can only have one, so you can only have a parent template, but there is a workaround to the method to achieve the reuse of multiple templates to the purpose, see the Manual of the use of the label


HTML escape
Mainly to help escape the < such as angle brackets;, &, "There can be two ways." One is to use labels, and the other is to use filters. In fact, twig internal is called PHP htmlspecialchars function

{{User.username|e}}
{{user.username|e (' JS ')}}

{% Autoescape true%}
Everything'll be automatically escaped in this block
{% Endautoescape%}
{{User.username|e}}
{{user.username|e (' JS ')}}

{% Autoescape true%}
Everything'll be automatically escaped in this block
{% Endautoescape%}
Because {{is Twig operator, if you need to output two curly braces, the simplest way is to

{{ '{{' }}
{{ '{{' }}
You can also use raw tags and raw filters, detailed reference manuals

{% RAW%}


      {% for item in seq%}
    • {{Item}}

    • {% ENDFOR%}

{% Endraw%}
{% RAW%}

      {% for item in seq%}
    • {{Item}}

    • {% ENDFOR%}

{% Endraw%}

Macros macro
Macros are a bit like functions and are often used to output some HTML tags.
Here is a simple example that defines a macro that outputs the input label.

{% macro input (name, value, type, size)%}

{% ENDMACRO%}
{% macro input (name, value, type, size)%}

The {% ENDMACRO%} macro parameter is not a default value, but you can do so through the default filter.
In general, macros are defined in other pages and then imported via the Import tab.
{% import "forms.html" as Forms%}

{{forms.input (' username ')}}


{% import "forms.html" as Forms%}

{{forms.input (' username ')}}

You can also import only a subset of the macros in a file, and you can rename them again.
{% from ' forms.html ' import input as Input_field, textarea%}


Username

{{Input_field (' username ')}}

Password

{{Input_field (' password ', type= ' password ')}}


{{textarea (' comment ')}}


{% from ' forms.html ' import input as Input_field, textarea%}


Username

{{Input_field (' username ')}}

Password

{{Input_field (' password ', type= ' password ')}}


{{textarea (' comment ')}}

The above code indicates that input and textarea macros were imported from forms.html and renamed input to Input_field.
An expression
Twig allows you to use expressions anywhere, his rules are almost identical to PHP, and even if you don't, PHP will still feel simple.
The simplest is
string: "Hello World" or ' Hello World '
Numbers: 42 or 42.33
Array: [' A ', ' B ', ' C ']
Hash: {' A ': ' av ', ' B ': ' BV '} where keys can be no quotation marks or numbers can also be an expression, such as {a: ' av ', b: ' BV '} {1: ' 1v ', 2: ' 2v '} {1+2: ' 12v '}
Logic: TRUE or False
And finally, there's null.
You can nest definitions
{% Set foo = [1, {"foo": "Bar"}]%}
{% Set foo = [1, {' foo ': ' Bar '}]%} operator
Includes numeric operations +-*/% (for remainder)//(DIVISIBLE) * * (exponentiation)

{{2 * 3}}=6

{{2 * 3}}=8

{{2 * 3}}=6

{{2 * 3}}=8 logical operation and OR not
Compare Operations > < >= <= = = = =
The code containing the operation in is returned true
{{1 in [1, 2, 3]}}
{{' cd ' in ' ABCDE '}}
{{1 in [1, 2, 3]}}
{{' cd ' in ' ABCDE '}} Test operation is this does not have to say directly to see the code
{{name is odd}}
{% If Loop.index is Divisibleby (3)%}
{% If Loop.index is not divisibleby (3)%}
{# is equivalent to #}
{% if not (Loop.index is Divisibleby (3))%}
{{name is odd}}
{% If Loop.index is Divisibleby (3)%}
{% If Loop.index is not divisibleby (3)%}
{# is equivalent to #}
{% if not (Loop.index is Divisibleby (3))%} other operators
.. Create an array that specifies the start to end, which is the abbreviation for the range function, see the manual

{% for I in 0..3%}
{{i}},
{% ENDFOR%}
{% for I in 0..3%}
{{i}},
{% ENDFOR%}

| Use a filter

{# output'll be HELLO #}
{"Hello" |upper}}
{# output'll be HELLO #}
{{"Hello" |upper}}~ Force string Connection
{"Hello" ~ Name ~ "!"}}
{"Hello" ~ Name ~ "!"}}?: Ternary operator
{{foo?} ' Yes ': ' No '}}
{{foo?} ' Yes ': ' No '}. [] Get the properties of an object, such as the following are equal.

{{Foo.bar}}
{{foo[' bar '}}
{{Foo.bar}}
{{foo[' bar '}}
You can also insert an expression inside a string, usually the expression is a variable. Format is an #{expression}
{"Foo #{bar} Baz"}}
{"Foo #{1 + 2} Baz"}}
{"Foo #{bar} Baz"}}
{"Foo #{1 + 2} Baz"}}


Blank control
Like PHP, the first line break after the Twig template tag is automatically deleted, and the rest of the blanks (including whitespace tab wrapping, etc.) are output as-is.
Use the spaceless tag to remove whitespace between these HTML tags

{% spaceless%}

Foo

{% endspaceless%}

{# output would be foo #}
{% spaceless%}

Foo

{% endspaceless%}

{# output would be foo #}
With the-operator, it is easy to delete the whitespace between the twig tag and the HTML tag before or after the label.
{% Set value = ' no spaces '%}
{#-No leading/trailing whitespace-#}
{%-If True-%}
{{-Value-}}
{%-endif-%}

{# output ' no spaces ' #}
{% Set value = ' no spaces '%}
{#-No leading/trailing whitespace-#}
{%-If True-%}
{{-Value-}}
{%-endif-%}

{# output ' no spaces ' #}
{% Set value = ' no spaces '%}

  • {{-value}}


  • {# outputs '
  • No spaces
  • ' #}
    {% Set value = ' no spaces '%}
  • {{-value}}
  • {# outputs '

  • No spaces
  • ' #}

    The end, if you insist on seeing here, congratulate yourself, you have mastered a little more knowledge, congratulations congratulations

    Excerpt from Jiaochangyun's column

    http://www.bkjia.com/PHPjc/478452.html www.bkjia.com true http://www.bkjia.com/PHPjc/478452.html techarticle wrote a few things about twig. I haven't written a quick start or something like that. Now write the profile twig template is normal text file, do not need special extension, ....

  • 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.