TWIG的 function 学习
目前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区块的内容。
<title>{% block title %}{% endblock %}</title> 
 
<h1>{{ block('title') }}</h1> 
 
{% block body %}{% endblock %} 
<title>{% block title %}{% endblock %}</title>
<h1>{{ block('title') }}</h1>
{% 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 %} 
    <h3>Table Of Contents</h3> 
    ... 
    {{ parent() }} 
{% endblock %} 
{% extends "base.html" %}
{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ parent() }}
{% endblock %}
random函数
1.5版本新增,从一个数组中随机返回一个
{{ random(['apple', 'orange', 'citrus']) }} 
{{ random(['apple', 'orange', 'citrus']) }}
	
相关新闻>>
- 发表评论
 - 
				
 
- 最新评论 进入详细评论页>>
 





![smarty局部缓存技术[源码分析]](/uploads/allimg/130827/11214T939-0-lp.jpg)