TWIG template design Quick Start manual chinese_php tutorial

Source: Internet
Author: User
TWIG template design Quick Start Manual (Chinese. I wrote several articles about twig .. I haven't written a quick start or something. Now, the template for writing the summary twig is a common text file without a special extension. I wrote several articles about twig .. I haven't written a quick start or something. Write Now

Summary
The twig template contains common extension files, and does not contain special extension names. you can use either. html. htm. twig.
The variables and expressions in the template will be parsed and replaced at runtime, and the tags will be used to control the template logic.
The following is the smallest template to illustrate some basic things.




My Webpage



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

  • {% Endfor %}


My Webpage
{A_variable }}





My Webpage



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

  • {% Endfor %}

My Webpage
{A_variable }}


There are two types of symbols: {%... %} and {...}. The first one is used to control the for loop, and the second one is used to output variables and expressions.


Ide support
Many IDEs support twig highlighting. Find what you 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 several variables to the template, and you need to output them in the template. For example, output $ hello

{Hello }}
{Hello} if an object or array is passed to the template, you can use dot. to output the attributes or methods of the object or the members of the array. Or you can use the following method.
{Foo. bar }}
{Foo ['bar']}
{Foo. bar }}
{Foo ['bar']}
If the Accessed value does not exist, null is returned. TWIG has a complete set of processes to check whether the value exists.


For. bar performs the following operations
... If foo is an array, the bar member is returned. if it does not exist, continue.
... If foo is an object, the bar attribute is returned. if it does not exist, continue.
... Will try to run the bar Method. if it does not exist, continue.
... Will try to run the getBar method. if it does not exist, continue.
... Will try to run the isBar method, if it does not exist, return null


For ['bar'] is much simpler. for must be an array, and the bar member is returned. if not, null is returned.
Global variables
TWIG defines some global variables.

_ Self. For more information, see the macro label.
_ Context: the current environment.
_ Charset: current character encoding


Variable assignment
For more information, see set tag.

{% 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 (|. The filter can also have parameters. Filters can also be used in multiple ways.
The following example uses two filters.

{Name | striptags | title }}
{Name | striptags | title} striptas indicates that the html tag is removed, and title indicates that the first letter of each word is capitalized. For more filters, see my blog


Filters can also be used in code blocks. For more information, see filter tags.

{% Filter upper %}
This text becomes uppercase
{% Endfilter %}
{% Filter upper %}
This text becomes uppercase
{% Endfilter %}

Function
This is nothing to say. anyone who writes the program knows that TWIG has some built-in functions. refer to my blog.
For example, if an array ranging from 0 to 3 is returned, the range function is used.
{% For I in range (0, 3) %}
{I }},
{% Endfor %}
{% For I in range (0, 3) %}
{I }},
{% Endfor %}

Process control
Supports the for loop and the if/elseif/else structure. Let's look at the example. there is 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 %}


Note
The content surrounded by {#... #} is commented out, which can be a single row or multiple rows.


Load other templates
For details, see The include tag (translated in my blog). The rendered content is returned to the current template.

{% Include 'sidebar.html '%}
{% Include 'sidebar.html '%} the variables in the current template will also be passed to the include template, where you can directly access the variables in your template.
For example

{% For box in boxes %}
{% Include "render_box.html" %}
{% Endfor %}
{% For box in boxes %}
{% Include "render_box.html" %}
{% Endfor %} can access the box variable in render_box.html.
By adding other parameters, the loaded template can only access some variables or cannot access them completely. Reference Manual


Template inheritance
The most useful feature of TWIG is template inheritance. it allows you to create a "skeleton template", and then you use different blocks to overwrite any part of the parent template. It is very easy to use.
First, we define a basic development page base.html that contains many block blocks, which can be overwritten by quilt templates.




{% Block head %}

{% Block title % }{% endblock %}-My Webpage
{% Endblock %}


{% Block content %} {% endblock %}



{% Block footer %}
©Copyright 2011 by you.
{% Endblock %}







{% Block head %}

{% Block title % }{% endblock %}-My Webpage
{% Endblock %}


{% Block content %} {% endblock %}



{% Block footer %}
©Copyright 2011 by you.
{% Endblock %}



We have defined four block blocks: block head, block title, block content, and block footer.
Note:
1. blocks can be nested.
2. you can set the default value for block (the content enclosed in the middle). if the sub-template does not overwrite, the default value is displayed directly. For example, block footer, you do not need to modify most pages (effort-saving), but you still need to modify them conveniently (flexibility)
Next I will see how to define the sub-template.
{% 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 that {% extends "base.html" %} must be the first tag. The block footer is not defined, so the default value set in the parent template is displayed.
If you need to add block 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 %}
There can only be one extends tag, so you can only have one parent template, but there is a way to reuse multiple templates. for details, see the use tag in the manual.


HTML escape
There are two methods to help escape angle brackets. One is to use tags, and the other is to use filters. In fact, TWIG calls the htmlspecialchars function of php internally.

{User. username | e }}
{User. username | e ('js ')}}

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

{% Autoescape true %}
Everything will be automatically escaped in this block
{% Endautoescape %}
Because {is the TWIG operator. if you need to output two curly braces, the easiest way is

{{'{{'}}
{{'{{'}}
You can also use raw tags and raw filters. For more information, see the manual.

{% Raw %}


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

  • {% Endfor %}

{% Endraw %}
{% Raw %}

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

  • {% Endfor %}

{% Endraw %}

Macros macro
Macros are similar to functions and are often used to output html tags.
Here is a simple example that defines a macro that outputs the input tag.

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

{% Endmacro %}
{% Macro input (name, value, type, size) %}

The {% endmacro %} macro parameter has no default value, but you can use the default filter.
Generally, macros are defined on other pages and imported using the import tag,
{% Import "forms.html" as forms %}

{Forms. input ('Username ')}}


{% Import "forms.html" as forms %}

{Forms. input ('Username ')}}

You can also import only some macros in a file and rename them.
{% 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 code above indicates that the input and textarea macros are imported from forms.html, and the input is renamed as input_field.
Expression
TWIG allows you to use expressions anywhere. its rules are almost the same as those of PHP, and even if you don't use PHP, you will still feel very simple.
The simplest one is:
String: "hello world" or "hello world'
Number: 42 or 42.33
Array: ['A', 'B', 'C']
Hash: {'a': 'Av', 'B': 'bv '} among them, keys can be either a pair of quotation marks, numbers, or expressions, such as {: 'Av', B: 'bv '} {1: '1v', 2: '2v'} {1 + 2: '123 '}
Logic: true or false
Finally, null exists.
You can nested definition
{% Set foo = [1, {"foo": "bar"}] %}
{% Set foo = [1, {"foo": "bar"}] %} operator
Including number calculation +-*/% (calculate the remainder) // (entire division) ** (multiplication)

{2*3 }}= 6

{2*3 }}= 8

{2*3 }}= 6

{2*3 }}= 8 logical operations and or not
Comparison calculation ><>==! =
The code that contains the operation in or below returns true.
{1 in [1, 2, 3]}
{'CD' in 'ABCDE '}}
{1 in [1, 2, 3]}
{'CD' in 'ABCDE'} the test operation is. check the code directly.
{Name is odd }}
{% If loop. index is pisibleby (3) %}
{% If loop. index is not pisibleby (3) %}
{# Is equivalent #}
{% If not (loop. index is pisibleby (3) %}
{Name is odd }}
{% If loop. index is pisibleby (3) %}
{% If loop. index is not pisibleby (3) %}
{# Is equivalent #}
{% If not (loop. index is pisibleby (3) %} Other operators
.. Create an array from the beginning to the end. this is the abbreviation of the range function. for details, see the manual.

{% For I in 0 .. 3%}
{I }},
{% Endfor %}
{% For I in 0 .. 3%}
{I }},
{% Endfor %}

| Use a filter

{# Output will be HELLO #}
{"Hello" | upper }}
{# Output will be HELLO #}
{"Hello" | upper }}~ Force string connection
{"Hello "~ Name ~ "! "}}
{"Hello "~ Name ~ "! "}}? : Ternary operators
{Foo? 'Yes': 'no '}}
{Foo? 'Yes': 'no'}. [] to get the attributes of an object. for example, the following are equal.

{Foo. bar }}
{Foo ['bar']}
{Foo. bar }}
{Foo ['bar']}
You can also insert an expression inside a string, which is usually a variable. Format: # {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 tag of the TWIG template will be automatically deleted, and the remaining blank spaces (including space tab line breaks) will be output as is.
Spaceless labels can be used to delete gaps between these HTML tags.

{% Spaceless %}


Foo


{% Endspaceless %}

{# Output will be

Foo

#}
{% Spaceless %}


Foo


{% Endspaceless %}

{# Output will be

Foo

#}
Using the-operator, you can easily delete the blank space between the TWIG tag and the html tag before or after the TWIG tag.
{% 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
  • '#}

    It's over. if you insist on seeing this, congratulations! you have learned more. Congratulations!

    From the column jiaochangyun

    Bytes .. I haven't written a quick start or something. Now, the template that writes the summary twig is a common text file and does not require a 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.