目前twig內建的函數包括
attribute, block, constant, cycle, dump, parent, random, range.
其實部分函數,在tags的學習裡已經見過了。
attribute函數
1.2版本新增
他就相當於是個. 操作符。
{{ attribute(object, method) }}
{{ attribute(object, method, arguments) }}
{{ attribute(array, item) }}
{{ attribute(object, method) }}
{{ attribute(object, method, arguments) }}
{{ attribute(array, item) }}
block函數
輸出block區塊的內容。
{% block title %}{% endblock %}
{{ block('title') }}
{% block body %}{% endblock %}
{% block title %}{% endblock %}
{{ block('title') }}
{% block body %}{% endblock %}
constant函數
讀取常量{{ some_date|date(constant('DATE_W3C')) }}
{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
{{ some_date|date(constant('DATE_W3C')) }}
{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
cycle函數
迴圈輸出數組的內容,
{% set fruits = ['apple', 'orange', 'citrus'] %}
{% for i in 0..10 %}
{{ cycle(fruits, i) }}
{% endfor %}
{% set fruits = ['apple', 'orange', 'citrus'] %}
{% for i in 0..10 %}
{{ cycle(fruits, i) }}
{% endfor %}
dump函數
1.5版本新增
列印變數,就是用的php的var_dump函數,
另外twig預設是沒有開啟debug模式的,你需要首先開啟他
$twig = new Twig_Environment($loader, $config);
$twig->addExtension(new Twig_Extension_Debug());
$twig = new Twig_Environment($loader, $config);
$twig->addExtension(new Twig_Extension_Debug());
你可以傳遞一個或者多個變數,如果你不傳遞變數,他會列印所有變數
{{ dump(user, categories) }}
{{ dump() }}
{{ dump(user, categories) }}
{{ dump() }}
parent函數
擷取父block的內容,在你準備增加而不是覆蓋的時候特別有用
{% extends "base.html" %}
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
{% extends "base.html" %}
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
random函數
1.5版本新增,從一個數組中隨機返回一個
{{ random(['apple', 'orange', 'citrus']) }}
{{ random(['apple', 'orange', 'citrus']) }}
range函數
返回一個數字數組,從第一個參數開始,到第二個參數結束(包含第二個),第三個參數是步長(可以省略)。 和0..10一樣
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
{# returns 0, 1, 2, 3 #}
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
{# returns 0, 1, 2, 3 #}
又學習了不少。。繼續呱唧呱唧。。邁向新的頁面。。。
摘自 jiaochangyun的專欄
http://www.bkjia.com/PHPjc/478457.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/478457.htmlTechArticle目前twig內建的函數包括 attribute, block, constant, cycle, dump, parent, random, range. 其實部分函數,在tags的學習裡已經見過了。 attribute函數 1.2版本新...