TWIG 模板设计 快速入门手册 中文

原文地址: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

require_once'/path/to/lib/Twig/Autoloader.php';

Twig_Autoloader::register();

 

 

记得用Twig所在路径代替/path/to/lib

 

2

require_once'/path/to/lib/Twig/Autoloader.php';

Twig_Autoloader::register();

 

 

注:Twig在类的命名上遵守PEAR的约定,这意味着你可以在自己编写的autoloader中整合对Twig的类的加载。

?

1

2

3

4

$loadernewTwig_Loader_String();

$twignewTwig_Environment($loader);

$template$twig->loadTemplate('Hello {{ name }}!');

$template->display(array('name'=> 'Fabien'));

2

require_once'/path/to/lib/Twig/Autoloader.php';

Twig_Autoloader::register();

 

Twig使用加载器(Twig_Loader_String)来定位模板,同时使用环境(Twig_Environment)来储存配置信息。

loadTemplate()方法使用加载器设定的信息来定位和加载模板,同时返回一个模板对象(Twig_Template),该对象可以使用display()方法来进行渲染。

Twig也可以使用文件系统加载器(filesystem loader):

?

1

2

3

4

5

$loadernewTwig_Loader_Filesystem('/path/to/templates');

$twignewTwig_Environment($loader,array(

'cache'=> '/path/to/compilation_cache',

));

$template$twig->loadTemplate('index.html');

 

 

  有关TWIG 模板引擎 快速入门手册需要原文、英文的朋友们,可以在这里找到     http://twig.sensiolabs.org/doc/templates.html

 

TWIG

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进行高亮支持

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 %}
                &copy; 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

  

  1. {{ user.username|e }}  
  2. {{ user.username|e('js') }}  
  3.   
  4. {% autoescape true %}  
  5.     Everything will be automatically escaped in this block  
  6. {% endautoescape %}  


因为{{是TWIG的操作符,如果你需要输出两个花括号,最简单到办法就是[html]view plain copy

  

  1. {{ '{{' }}  


还可以使用 raw 标签和raw 过滤器,详细参考手册[html]view plain copy

  

  1. {% raw %}  
  2.     <ul>  
  3.     {% for item in seq %}  
  4.         <li>{{ item }}</li>  
  5.     {% endfor %}  
  6.     </ul>  
  7. {% endraw %}  

 

macros宏

宏有点类似于函数,常用于输出一些html标签。

这里有个简单示例,定义了一个输出input标签的宏。

[html]view plain copy

  

  1. {% macro input(name, value, type, size) %}  
  2.     <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />  
  3. {% endmacro %}  

宏参数是没有默认值的,但你可以通过default过滤器来实现。一般来说宏会定义在其他到页面,然后通过import标签来导入,[html]view plain copy

  

  1. {% import "forms.html" as forms %}  
  2.   
  3. <p>{{ forms.input('username') }}</p>  

你也可以只导入一个文件中部分宏,你还可以再重命名。[html]view plain copy

  

  1. {% from 'forms.html' import input as input_field, textarea %}  
  2.   
  3. <dl>  
  4.     <dt>Username</dt>  
  5.     <dd>{{ input_field('username') }}</dd>  
  6.     <dt>Password</dt>  
  7.     <dd>{{ input_field('password', type='password') }}</dd>  
  8. </dl>  
  9. <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

  

  1. {% set foo = [1, {"foo": "bar"}] %}  

运算符

包括数字运算+ - * /  %(求余数)  //(整除) **(乘方)

[html]view plain copy

  

  1. <p>{{ 2 * 3 }}=6  
  2. <p>{{ 2 * 3 }}=8  

逻辑运算 and or  not

比较运算 > < >= <= == !=

包含运算 in 以下的代码会返回 true[html]view plain copy

  

  1. {{ 1 in [1, 2, 3] }}  
  2. {{ 'cd' in 'abcde' }}  

测试运算 is 这个不用多说 直接看代码[html]view plain copy

  

  1. {{ name is odd }}  
  2. {% if loop.index is divisibleby(3) %}  
  3. {% if loop.index is not divisibleby(3) %}  
  4. {# is equivalent to #}  
  5. {% if not (loop.index is divisibleby(3)) %}  

其他操作符

.. 建立一个指定开始到结束的数组,他是range函数的缩写,具体参看手册

[html]view plain copy

  

  1. <pre name="code" class="html">{% for i in 0..3 %}  
  2.     {{ i }},  
  3. {% endfor %}</pre>  
  4. <pre></pre>  

| 使用一个过滤器

[html]view plain copy

  

  1. {# output will be HELLO #}  
  2. {{ "hello"|upper }}  

~ 强制字符串连接[html]view plain copy

  

  1. {{ "Hello " ~ name ~ "!" }}  

?:  三元操作符[html]view plain copy

  

  1. {{ foo ? 'yes' : 'no' }}  

. [] 得到一个对象的属性,比如以下是相等的。[html]view plain copy

  

  1. {{ foo.bar }}  
  2. {{ foo['bar'] }}  


你还可以在一个字符串内部插入一个表达式,通常这个表达式是变量。 格式是 #{表达式}[html]view plain copy

  

  1. {{ "foo #{bar} baz" }}  
  2. {{ "foo #{1 + 2} baz" }}  

 

空白控制

和 php一样,在TWIG模板标签之后的第一个换行符会被自动删掉,其余的空白(包括 空格 tab 换行等)都会被原样输出。

使用spaceless标签就可以删除这些HTML标签之间的空白

[html]view plain copy

  

  1. {% spaceless %}  
  2.     <div>  
  3.         <strong>foo</strong>  
  4.     </div>  
  5. {% endspaceless %}  
  6.   
  7. {# output will be <div><strong>foo</strong></div> #}  


使用-操作符,可以很方便的删除TWIG标签之前或之后与html标签之间的空白。[html]view plain copy

  

  1. {% set value = 'no spaces' %}  
  2. {#- No leading/trailing whitespace -#}  
  3. {%- if true -%}  
  4.     {{- value -}}  
  5. {%- endif -%}  
  6.   
  7. {# output 'no spaces' #}  

[html]view plain copy

  

  1. {% set value = 'no spaces' %}  
  2. <li>    {{- value }}    </li>  
  3.   
  4. {# 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

require_once'/path/to/lib/Twig/Autoloader.php';

Twig_Autoloader::register();

 

 

 

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 %}

 

判断是否是用户

 
  1. {% if users %}

  2. <ul>

  3. {% for user in users %}

  4. <li>{{ user.username }}</li>

  5. {% endfor %}

  6. </ul>

  7. {% endif %}

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值