TWIG的 function 學習_PHP教程

來源:互聯網
上載者:User
目前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版本新...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.