Home > Article > Backend Development > Twig's tags learning (Chinese) Part 1_PHP tutorial
Twig is a simple yet powerful template. I’m learning SF so take a look at her.
The source of this article is http://twig.sensiolabs.org/doc/tags/index.html
Currently supported tags include
for if macro filter set extends block include import from use spaceless autoescape raw flush do
twig is divided into 3 types in html
{{...}} directly outputs the variables
{#...#} comment tag
{%...%} command tags are what we need to learn
for tag
This is the simplest, it is a loop.
Array-based loop
{% for i in 0..10 %}
* {{ i }}
{% endfor %}
{% for i in 0..10 %}
* {{ i }}
{% endfor %}
Letter-based loop
* {{ letter }}
{% endfor %}
{% for letter in 'a'..'z' %}
* {{ letter }}
{% endfor %}
Variables inside the loop body
loop.length, loop.revindex, loop.revindex0, loop.last These values are only valid when the loop is a PHP array or a class that implements the Countable interface.
Add a condition
Unlike PHP, break and continue statements are not supported inside loops. You can only skip some loops through filters, like this
If users is an empty array, no user found will be output.
{% else %}
{% endfor %}
{% for key in users|keys %}
{% endfor %}
{% for key, user in users %}
{% endfor %}
{% if kenny.sick %}
Kenny is sick.
{% elseif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
{% if users %}
Macro (macro tag) is similar to functions in other languages and is often used to fill in html tags. The following is an example to render
{% macro input(name, value, type, size) %}
{% endmacro %}
{% macro input(name, value, type, size) %}
{% endmacro %}
macro与函数的不同之处在于:
1、参数的默认值是通过macro块内部的 default过滤器来定义的。
2、参数总是可选的。
另外,就跟php函数一样,macro内部是无法使用外部的变量的。但你可以传递一个特殊变量_context作为参数来获取整个内容。
macro可以被定义在任何的模板内,但在你使用之前需要使用 imported
{% import "forms.html" as forms %}
{% import "forms.html" as forms %}然后就可以这样使用了
{{ forms.input('username') }}
{{ forms.input('password', null, 'password') }}
{{ forms.input('username') }}
{{ forms.input('password', null, 'password') }}
如果你要在定义macro的模板里使用,就不需要imported 可以使用特殊变量_self
{{ _self.input('username') }}
{{ _self.input('username') }}
{% macro input(name, value, type, size) %}
{% endmacro %}
{% macro wrapped_input(name, value, type, size) %}
{% macro wrapped_input(name, value, type, size) %}
{# forms.html #}
{% macro input(name, value, type, size) %}
{% endmacro %}
{# shortcuts.html #}
{% macro wrapped_input(name, value, type, size) %}
{% import "forms.html" as forms %}
{% macro input(name, value, type, size) %}
{% endmacro %}
{# shortcuts.html #}
{% macro wrapped_input(name, value, type, size) %}
{% import "forms.html" as forms %}
filter tag
Just apply a filter to the entire block
{% filter upper %}
This text becomes uppercase
{% endfilter %}
{% filter upper %}
This text becomes uppercase
{% endfilter %}
{% filter lower|escape %}
SOME TEXT
{% endfilter %}
Excerpted from jiaochangyun’s column