symfony中twig的模板過濾器

過濾器

變量能夠被過濾器修飾。過濾器和變量用(|)分割開。過濾器也是能夠有參數的。過濾器也能夠被多重使用。php

通用過濾器

date過濾器

1.1版本新增時區支持,1.5版本增長了默認的日期格式。
格式化時間,這個過濾器和php的date函數無限相似,可處理與 strtotime 兼容的字符串,或 DateTime/DateInterval 的實例,可選的第二個參數用於指定時區,若是所修飾的數據爲空則默認爲當前時間css

{{ article.publishedTime|date(‘Y-m-d H:i:s’) }}

輸出: 2014-7-12 12:11:11html

format過濾器

和php的printf函數同樣,用來替換佔位符json

<span class=」days」> {{ 「%02d」|format(countdown.days) }} </span>天

輸出: 12天api

replace過濾器

{{ 「教師可在直播開始前%hour%小時內進入直播教室,以準備相關教學資料.」 |replace({‘%hour%’: hour}) }}

輸出: 教師可在直播開始前1小時內進入直播教室,以準備相關教學資料.數組

number_format過濾器

他是php函數 number_format的一個包裝 直接見函數參考php函數 number_format吧安全

<span class=」rating-num」> {{ course.rating|number_format(1) }}分 </span>

輸出: 5分函數

url_encode過濾器

編碼連接字符串,等同於php函數urlencode編碼

{{ data|url_encode() }}

json_encode過濾器

編碼JSON格式,等同於php函數json_encodeurl

{{ data|json_encode() }}

convert_encoding過濾器

編碼轉換,第一個參數指定轉換後的編碼,第二個參數指定轉換前的編碼,本函數依賴於iconv 或者mbstring 因此至少須要安裝一個

{{ data|convert_encoding(‘UTF-8’, ‘iso-2022-jp’) }}

title過濾器

將字符串中每一個單詞的首字母大寫,等同於 ucwords

{{ ‘my first car’|title }}

輸出: My First Car

capitalize過濾器

將字符串的首字母大寫,其他字母小寫的格式,等同於 ucfirst

{{ ‘my first car’|capitalize }}

輸出: My first car

nl2br過濾器

將字符串裏的 \n 替換成 <br/>

{{ 「I like Twig.\nYou will like it too.」|nl2br }}

輸出: 
I like Twig. <br />
You will like it too.

join過濾器

將數組的各個元素按指定分隔符組成字符串

{{ [1, 2, 3]|join }}

輸出: 123

{{ [1, 2, 3]|join(‘|’) }}

輸出: 1|2|3

reverse 過濾器

反轉一個數組,或者是一個實現了Iterator接口的對象,在 array_reverse 的基礎上增長了對字符串的處理

{% for use in users|reverse %} … {% endfor %}

length過濾器

返回一個數組或者字符串的長度,等同於 count 和 strlen 的結合體

{% if users|length > 10 %} … {% endif %}

sort過濾器

對數組排序

{% for use in users|sort %} … {% endfor %}

keys過濾器

將數組的所有鍵名提取成一個數組,等同於 array_keys

{% for key in array|keys %} … {% endfor %}

escape過濾器

將字符串安全地處理成合法的指定數據,支持多種轉換模式,默認模式爲 html,其餘可選模式有 html_attr、js、css、url,主要轉義 & < > ‘ 」 。而且它有個簡寫方式 e。

{{ user.username|escape }} {{ user.username|e }}

raw過濾器

用於在autoescape標籤內部,標記出不須要轉義的內容。

<div class=」thread-body」> {{article.body |raw }} </div>

merge過濾器

用來合併數組,近似於 array_merge 。如 {{ 數組1|merge(數組2) }} 

{% set items = { ‘id’:course.id} %} {% set items = items|merge({type:’all’}) %}
相關文章
相關標籤/搜索