原文地址:https://blog.csdn.net/chajinglong/article/details/51839250
必要條件
Twig需要的最低PHP版本爲5.2.4。
安裝Subversion或者Git
SVN地址:http://svn.twig-project.org/trunk/, git地址git://github.com/fabpot/Twig.git
使用Twig的第一步是註冊它的autoloader:
2 |
|
記得用Twig所在路徑代替/path/to/lib
2 |
|
注:Twig在類的命名上遵守PEAR的約定,這意味着你可以在自己編寫的autoloader中整合對Twig的類的加載。
1 2 3 4 |
|
2 |
|
Twig使用加載器(Twig_Loader_String)來定位模板,同時使用環境(Twig_Environment)來儲存配置信息。
loadTemplate()方法使用加載器設定的信息來定位和加載模板,同時返回一個模板對象(Twig_Template),該對象可以使用display()方法來進行渲染。
Twig也可以使用文件系統加載器(filesystem loader):
1 2 3 4 5 |
|
有關TWIG 模板引擎 快速入門手冊需要原文、英文的朋友們,可以在這裏找到 http://twig.sensiolabs.org/doc/templates.html
The flexible, fast, and secure
template engine for PHP
Twig for Template Designers( Twig摸板設計者)
以下文章描述的是Twig魔板引擎和將要更好的使用創建Twig模板而生。
twig 的模板就是普通的文本文件,也不需要特別的擴展名,.html .htm .twig 都可以。
模板內的 變量 和 表達式 會在運行的時候被解析替換,標籤(tags)會來控制模板的邏輯
下面是個最小型的模板,用來說明一些基礎的東西:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <head> <title>My Webpage</title> </head> <body> <ul id="navigation"> {% for item in navigation %} <li><a href="{{ item.href }}">{{ item.caption }}</a></li> {% endfor %} </ul> <h1>My Webpage</h1> {{ a_variable }} </body> </html> |
裏邊包含兩種符號{% ...%}和{{ ... }}第一種用來控制的比如for循環...,第二種是用來輸出變量和表達式的。
IDEs Integration¶
IDEs 支持
對於很多IDEs都對twig進行高亮支持
- Textmate via the Twig bundle
- Vim via the Jinja syntax plugin or the vim-twig plugin
- Netbeans via the Twig syntax plugin (until 7.1, native as of 7.2)
- PhpStorm (native as of 2.1)
- Eclipse via the Twig plugin
- Sublime Text via the Twig bundle
- GtkSourceView via the Twig language definition (used by gedit and other projects)
- Coda and SubEthaEdit via the Twig syntax mode
- Coda 2 via the other Twig syntax mode
- Komodo and Komodo Edit via the Twig highlight/syntax check mode
- Notepad++ via the Notepad++ Twig Highlighter
- Emacs via web-mode.el
- Atom via the PHP-twig for atom
Also, TwigFiddle is an online service that allows you to execute Twig templates from a browser; it supports all versions of Twig.
Variables(變量)
程序會傳遞給模板若干變量,需要在模板中找到它。
1 2 |
{{ foo.bar }} {{ foo['bar'] }} |
如果你訪問的值不存在就會返回null。TWIG有一整套的流程來確認值是否存在。
for.bar會進行一下操作
如果 foo是個數組,就嘗試返回bar成員,如果不存在的話,往下繼續
。。。如果foo是個對象,會嘗試返回bar屬性,如果不存在的話,往下繼續
。。。會嘗試運行bar方法,如果不存在的話,往下繼續
。。。會嘗試運行getBar方法,如果不存在的話,往下繼續
。。。會嘗試運行isBar方法,如果不存在的話,返回null
for['bar'] 就簡單很多了 for必須是個數組,嘗試返回bar成員,如果不就返回null
全局變量
TWIG定義了有一些全局變量
- _self 這個參看macro標籤
- _context 這個就是當前的環境
- _charset: 當前的字符編碼
變量賦值
具體參加set標籤
1 2 3 |
{% set foo = 'foo' %} {% set foo = [1, 2] %} {% set foo = {'foo': 'bar'} %} |
過濾器 Firters
變量可以被過濾器修飾。過濾器和變量用(|)分割開。過濾器也是可以有參數的。過濾器也可以被多重使用。
下面這例子就使用了兩個過濾器。
1 |
{{ name|striptags|title }} |
Striptags表示去除html標籤,title表示每個單詞的首字母大寫。
1 |
{{ list|join(', ') }} |
To apply a filter on a section of code, wrap it in the filter tag:
1 2 3 |
{% filter upper %} This text becomes uppercase {% endfilter %} |
函數 Function
這個沒什麼好說的,會寫程序的都知道,TWIG內置了一些函數,參考我的博客
舉個例子 返回一個0到3的數組,就使用 range函數
{% for i in range(0, 3) %} {{ i }}, {% endfor %}
命名結構
新版本1.12:支持命名構造增加了Twig1.12.
{% for i in range(low=1, high=10, step=2) %} {{ i }}, {% endfor %}
2 3 4 5 |
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} {# versus #} {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} |
流程控制
支持for循環 和 if/elseif/else結構。直接看例子吧,沒什麼好說的。
2 3 4 5 |
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} {# versus #} {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} |
<h1>Members</h1> <ul> {% for user in users %} <li>{{ user.username|e }}</li> {% endfor %} </ul> |
The if tag can be used to test an expression:
1 2 3 4 5 6 7 |
{% if users|length > 0 %} <ul> {% for user in users %} <li>{{ user.username|e }}</li> {% endfor %} </ul> {% endif %} |
2 3 4 5 |
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} {# versus #} {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} |
註釋
{# ... #} 包圍的內容會被註釋掉,可以是單行 也可以是多行。
2 3 4 5 |
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} {# versus #} {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} |
{# note: disabled template because we no longer use this {% for user in users %} ... {% endfor %} #}
載入其他模板
詳見include標籤(我博客內已經翻譯好哦),會返回經過渲染的內容到當前的模板裏
1 |
{{ include('sidebar.html') }} |
1 2 3 |
{% for box in boxes %} {{ include('render_box.html') }} {% endfor %} |
1 |
{{ include('sections/articles/sidebar.html') }} |
This behavior depends on the application embedding Twig.
2 3 4 5 |
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} {# versus #} {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} |
模板繼承
TWIG中最有用到功能就是模板繼承,他允許你建立一個“骨骼模板”,然後你用不同到block來覆蓋父模板中任意到部分。而且使用起來非常到簡單。
我們先定義一個基本骨骼頁base.html 他包含許多block塊,這些都可以被子模板覆蓋。
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <head> {% block head %} <link rel="stylesheet" href="style.css" /> <title>{% block title %}{% endblock %} - My Webpage</title> {% endblock %} </head> <body> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} © Copyright 2011 by <a href="http://domain.invalid/">you</a>. {% endblock %} </div> </body> </html> |
{% extends "base.html" %} {% block title %}Index{% endblock %} {% block head %} {{ parent() }} <style type="text/css"> .important { color: #336699; } </style> {% endblock %} {% block content %} <h1>Index</h1> <p class="important"> Welcome to my awesome homepage. </p> {% endblock %}
|
|
我們定義了4個block塊,分別是 block head, block title, block content, block footer
注意
1、block是可以嵌套的。
2、block可以設置默認值(中間包圍的內容),如果子模板裏沒有覆蓋,那就直接顯示默認值。比如block footer ,大部分頁面你不需要修改(省力),但你需要到時候仍可以方便到修改(靈活)
下面我看下 子模板應該怎麼定義。
HTML轉義
主要是幫助轉義 尖括號等 <, >, &, " 可以有兩種辦法。一種是用標籤,另一種是使用過濾器。其實TWIG內部就是調用 php 的htmlspecialchars 函數
[html]view plain copy
- {{ user.username|e }}
- {{ user.username|e('js') }}
- {% autoescape true %}
- Everything will be automatically escaped in this block
- {% endautoescape %}
因爲{{是TWIG的操作符,如果你需要輸出兩個花括號,最簡單到辦法就是[html]view plain copy
- {{ '{{' }}
還可以使用 raw 標籤和raw 過濾器,詳細參考手冊[html]view plain copy
- {% raw %}
- <ul>
- {% for item in seq %}
- <li>{{ item }}</li>
- {% endfor %}
- </ul>
- {% endraw %}
macros宏
宏有點類似於函數,常用於輸出一些html標籤。
這裏有個簡單示例,定義了一個輸出input標籤的宏。
[html]view plain copy
- {% macro input(name, value, type, size) %}
- <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
- {% endmacro %}
宏參數是沒有默認值的,但你可以通過default過濾器來實現。一般來說宏會定義在其他到頁面,然後通過import標籤來導入,[html]view plain copy
- {% import "forms.html" as forms %}
- <p>{{ forms.input('username') }}</p>
你也可以只導入一個文件中部分宏,你還可以再重命名。[html]view plain copy
- {% from 'forms.html' import input as input_field, textarea %}
- <dl>
- <dt>Username</dt>
- <dd>{{ input_field('username') }}</dd>
- <dt>Password</dt>
- <dd>{{ input_field('password', type='password') }}</dd>
- </dl>
- <p>{{ textarea('comment') }}</p>
上面的代碼表示 從forms.html中導入了 input 和 textarea宏,並給input重命名爲input_field。
表達式
TWIG允許你在任何地方使用表達式,他的規則和PHP幾乎一模一樣,就算你不會PHP 仍然會覺得很簡單。
最簡單的有
字符串:“hello world” 或者 'hello world'
數字:42 或者 42.33
數組:['a','b','c']
哈希:{'a':'av', 'b':'bv'} 其中keys 可以不要引號 也可以是數字 還可以是一個表達式,比如{a:'av', b:'bv'} {1:'1v', 2:'2v'} {1+2:'12v'}
邏輯: true 或者 false
最後還有null
你可以嵌套定義[html]view plain copy
- {% set foo = [1, {"foo": "bar"}] %}
運算符
包括數字運算+ - * / %(求餘數) //(整除) **(乘方)
[html]view plain copy
- <p>{{ 2 * 3 }}=6
- <p>{{ 2 * 3 }}=8
邏輯運算 and or not
比較運算 > < >= <= == !=
包含運算 in 以下的代碼會返回 true[html]view plain copy
- {{ 1 in [1, 2, 3] }}
- {{ 'cd' in 'abcde' }}
測試運算 is 這個不用多說 直接看代碼[html]view plain copy
- {{ name is odd }}
- {% if loop.index is divisibleby(3) %}
- {% if loop.index is not divisibleby(3) %}
- {# is equivalent to #}
- {% if not (loop.index is divisibleby(3)) %}
其他操作符
.. 建立一個指定開始到結束的數組,他是range函數的縮寫,具體參看手冊
[html]view plain copy
- <pre name="code" class="html">{% for i in 0..3 %}
- {{ i }},
- {% endfor %}</pre>
- <pre></pre>
| 使用一個過濾器
[html]view plain copy
- {# output will be HELLO #}
- {{ "hello"|upper }}
~ 強制字符串連接[html]view plain copy
- {{ "Hello " ~ name ~ "!" }}
?: 三元操作符[html]view plain copy
- {{ foo ? 'yes' : 'no' }}
. [] 得到一個對象的屬性,比如以下是相等的。[html]view plain copy
- {{ foo.bar }}
- {{ foo['bar'] }}
你還可以在一個字符串內部插入一個表達式,通常這個表達式是變量。 格式是 #{表達式}[html]view plain copy
- {{ "foo #{bar} baz" }}
- {{ "foo #{1 + 2} baz" }}
空白控制
和 php一樣,在TWIG模板標籤之後的第一個換行符會被自動刪掉,其餘的空白(包括 空格 tab 換行等)都會被原樣輸出。
使用spaceless標籤就可以刪除這些HTML標籤之間的空白
[html]view plain copy
- {% spaceless %}
- <div>
- <strong>foo</strong>
- </div>
- {% endspaceless %}
- {# output will be <div><strong>foo</strong></div> #}
使用-操作符,可以很方便的刪除TWIG標籤之前或之後與html標籤之間的空白。[html]view plain copy
- {% set value = 'no spaces' %}
- {#- No leading/trailing whitespace -#}
- {%- if true -%}
- {{- value -}}
- {%- endif -%}
- {# output 'no spaces' #}
[html]view plain copy
- {% set value = 'no spaces' %}
- <li> {{- value }} </li>
- {# outputs '<li>no spaces </li>' #}
感謝,百忙之中看完了文檔,如有什麼疑問,可以留言。
2 3 4 5 |
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} {# versus #} {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} |
2 |
|
OctoberCms 所使用的twig模板
<ul>
{% for user in users %}
<li> {{ user.username }}</li>
{% else %}
<li> <em> There are no users found </em></li>
{% endfor %}
</ul>
{% for letter in 'a' |upper..'z' |upper %}
-{{ letter }}
{% endfor %}
判斷是否是用戶
-
{% if users %}
-
<ul>
-
{% for user in users %}
-
<li>{{ user.username }}</li>
-
{% endfor %}
-
</ul>
-
{% endif %}