twig的 function 学习

目前twig内建的函数包括

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

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

attribute函数

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

block函数

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

<h1>{{ block('title') }}</h1>

{% block body %}{% endblock %}

constant函数

读取常量
  1. {{ some_date|date(constant('DATE_W3C')) }} 
  2. {{ constant('Namespace\\Classname::CONSTANT_NAME') }} 
{{ some_date|date(constant('DATE_W3C')) }}
{{ constant('Namespace\\Classname::CONSTANT_NAME') }}

cycle函数

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

{% for i in 0..10 %}
    {{ cycle(fruits, i) }}
{% endfor %}

dump函数

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

parent函数

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

{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ parent() }}
{% endblock %}

random函数

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

range函数

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

{# returns 0, 1, 2, 3 #}
原文地址:https://www.cnblogs.com/Kakasi/p/2881013.html