PHP Twig模版的function详解(中文)

来源:互联网 发布:使用波士顿矩阵实例 编辑:程序博客网 时间:2024/06/06 09:59

目前twig内建的函数包括

      attribute, block, constant, cycle, dump, parent, random, range.

其实部分函数,在tags的学习里已经见过了。


attribute函数

1.2版本新增
他就相当于是个. 操作符。
[html]view plaincopyprint?
  1. {{ attribute(object, method) }}  
  2. {{ attribute(object, method, arguments) }}  
  3. {{ attribute(array, item) }}  


block函数

输出block区块的内容。
[html]view plaincopyprint?
  1. <title>{% block title %}{% endblock %}</title>  
  2.   
  3. <h1>{{ block('title') }}</h1>  
  4.   
  5. {% block body %}{% endblock %}  


constant函数

读取常量
[html]view plaincopyprint?
  1. {{ some_date|date(constant('DATE_W3C')) }}  
  2. {{ constant('Namespace\\Classname::CONSTANT_NAME') }}  


cycle函数

循环输出数组的内容,
[html]view plaincopyprint?
  1. {% set fruits = ['apple', 'orange', 'citrus'] %}  
  2.   
  3. {% for i in 0..10 %}  
  4.     {{ cycle(fruits, i) }}  
  5. {% endfor %}  


dump函数

1.5版本新增
打印变量,就是用的php的var_dump函数,
另外twig默认是没有开启debug模式的,你需要首先开启他
[php]view plaincopyprint?
  1. $twig = new Twig_Environment($loader$config);  
  2. $twig->addExtension(new Twig_Extension_Debug());  
你可以传递一个或者多个变量,如果你不传递变量,他会打印所有变量
[html]view plaincopyprint?
  1. {{ dump(user, categories) }}  
  2. {{ dump() }}  


parent函数

获取父block的内容,在你准备增加而不是覆盖的时候特别有用
[html]view plaincopyprint?
  1. {% extends "base.html" %}  
  2.   
  3. {% block sidebar %}  
  4.     <h3>Table Of Contents</h3>  
  5.     ...  
  6.     {{ parent() }}  
  7. {% endblock %}  


random函数

1.5版本新增,从一个数组中随机返回一个
[html]view plaincopyprint?
  1. {{ random(['apple', 'orange', 'citrus']) }}  


range函数

返回一个数字数组,从第一个参数开始,到第二个参数结束(包含第二个),第三个参数是步长(可以省略)。 和0..10一样
[html]view plaincopyprint?
  1. {% for i in range(0, 3) %}  
  2.     {{ i }},  
  3. {% endfor %}  
  4.   
  5. {# returns 0, 1, 2, 3 #}  
0 0
原创粉丝点击