个性化阅读
专注于IT技术分析

每个开发人员都应了解的10条Twig技巧和基本功能

点击下载

本文概述

Twig是PHP编程语言的模板引擎。它的语法源自Jinja和Django模板。它是根据BSD许可获得许可的开放源代码产品, 由Fabien Potencier维护。初始版本由Armin Ronacher创建。

尽管是功能最齐全的PHP模板引擎之一, 但Twig还​​是最快的引擎:

图书馆 Time (sec) Memory (Ko) 每秒渲染的模板
枝条 3 1, 190 3333
PHPTAL 3.8 2, 100 2, 632
杜宇 6.9 1, 870 1, 449
聪明人2 12.9 2, 350 775
聪明人3 14.9 3, 230 671
卡里普索 34.3 620 292
eZ模板 53 5, 850 189

Twig是一种使你的php对象更多, 杂乱且易于阅读的方法。

在本文中, 我们将共享10个技巧和基础的集合, 每个开发人员都应该知道如何在Twig中进行操作。

10.变量声明

你可以将值分配给代码块内的变量。作业使用set标签:

{% set fooA = 'foo' %}
{% set fooB = [1, 2] %}
{% set fooC = {
    'foo': 'bar', 'foo2': 'bar2', 'group': fooB
} %}

{{ fooC.foo }}
{{ fooC.group[0]}}

Twig允许你操作变量中的多个值。你可以使用JSON-like表示法处理对象。

如果变量具有(PHP对象的方法或属性, 或PHP数组的项目)或所谓的”下标”语法([index]), 则可以使用点(。)来访问该变量的属性。

请注意, 如果属性包含特殊字符(如点或减号:myVariable.my-property或myVariable.my.property), 则你将需要使用attribute函数来访问它, 因为语法通常会导致Twig错误:

{{ attribute(myVariable, 'my-property') }}

{{ attribute(myVariable, 'my.property') }}

9.字符串插值

就像PHP在双引号之间使用变量一样:

<?php

$hello = "Hi";

echo "Inline $hello";
// Outputs : Inline Hi

$myVariable = "Hello {$hello}";
echo $myVariable;
// Outputs: "Hello Hi"

Twig也支持此功能, 你甚至可以使用串联和数学变量执行内联操作:

{% set name = 'Hello Buddy' %}
 
{{ "Hi #{name}, how are you today" }}
Hi Hello Buddy, how are you today

{{ "A math operation =  #{(1 + 2) * (4 * 5)}" }}
A math operation =  60

注意:如果要插值, 请始终使用双引号(“”), 如果使用单引号(“), 则不使用插值。

8. for循环和else标记内的循环变量

在{%for%}循环块内, 你可以访问包含以下属性的特殊变量循环:

变量 描述
循环索引 循环的当前迭代。 (1个已索引)
loop.index0 循环的当前迭代。 (0索引)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
循环优先 如果第一次迭代为真
最后循环 如果最后一次迭代则为真
循环长度 序列中的项目数
loop.parent 父上下文

例如, 要检查某项是否是迭代的最后一个, 可以使用:

{% for user in users %}
    {% if loop.last %}
        {{"Last user is : " ~ user.username}}
    {% else %}
        {{user.username}}
    {% endif %}
{% endfor %}

注意:loop.length, loop.revindex, loop.revindex0和loop.last变量仅适用于PHP数组或实现Countable接口的对象。当条件循环时, 它们也不可用。

尽管{%for%}标签不是{%if%}标签(你不会说), 但它支持{%else%}标签。如果要迭代的变量为空, 它将自动成为条件。

<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% else %}
        <li><em>no users available</em></li>
    {% endfor %}
</ul>

尽管else标签很有用, 但是你可以使用is iterable语句检查变量是否可迭代:

{# evaluates to true if the foo variable is iterable #}
{% if users is iterable %}
    {% for user in users %}
        Hello {{ user }}!
    {% endfor %}
{% else %}
    {# users is probably a string #}
    Hello {{ users }}!
{% endif %}

有时, 当使用嵌套循环时, 你需要访问父上下文。始终可以通过loop.parent变量访问父上下文。例如, 如果你具有以下模板数据:

{% set data = {
    'topics' : {
        'topic1' : ['Message 1 of topic 1', 'Message 2 of topic 1'], 'topic2' : ['Message 1 of topic 2', 'Message 2 of topic 2'], }
}%}

{% for topic, messages in data.topics %}
    * {{ loop.index }}: {{ topic }}
  {% for message in messages %}
      - {{ loop.parent.loop.index }}.{{ loop.index }}: {{ message }}
  {% endfor %}
{% endfor %}

输出应如下所示:

* 1: topic1
        - 1.1: Message 1 of topic 1
        - 1.2: Message 2 of topic 1
    * 2: topic2
        - 2.1: Message 1 of topic 2
        - 2.2: Message 2 of topic 2

7.扩展一个块而不删除现有内容

如果你有一个位于其他文件中的现有块(例如:base.html.twig), 则需要在生成视图(即child.html.twig)中追加更多内容到现有块中(在此示例中, 更多链接) ), 你可以在子视图中创建一个具有相同名称的块, 并使用parent()函数检索原始块的内容(如果没有父函数, 则仅替换该块, 而不会使用父模板的内容不存在)。

{# parent-index.html.twig#}

{%block toolbar -%}
    <a href="path_to_something">
        User Normal Action 1
    </a>
    <a href="path_to_something">
        User Normal Action 2
    </a>
{%endblock%}

{# child-template.html.twig#}

{%block toolbar -%}
    {# The content of the base.html.twig will be retrieved and printed in this inherited view too#}
    {{parent()}}
    
    <a href="path_to_something">
        User Normal Action 3
    </a>
    <a href="path_to_something">
        User Normal Action 4
    </a>
{%endblock%}

{#
    Final Output in the child-template :

    <a href="path_to_something">
        User Normal Action 1
    </a>
    <a href="path_to_something">
        User Normal Action 2
    </a>
    <a href="path_to_something">
        User Normal Action 3
    </a>
    <a href="path_to_something">
        User Normal Action 4
    </a>
#}

如果你仍然不了解它, 请阅读以下文章, 以全面了解父级的工作原理。

6. Twig支持正则表达式

Twig支持出色的字符串捷径, 可用于带有string()的基本任务和常见任务, 以及诸如start和end的出色功能:

{% if 'Batman' starts with 'B' %}

{% else%}
    
{% endif %}

{% if 'Batman' ends with 'n' %}

{% else%}
    
{% endif %}

但是, 并非生活中的一切都是开始或结束的。有时, 你需要根据需要实现更复杂的比较机制, 并且可能需要使用Regex解决。

Twig支持正则表达式, 你可以使用matchs语句使用它们。

{% if "mail@mail.com" matches '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2, })$/' %}
    {{"Is a valid mail"}}
{% else %}
    {{"It doesn't seems to be a valid mail buddy."}}
{% endif %}

5.打印变量时控制空格

Twig通常在标签之间包含任何空格, 即:

{% for i in 1..10 %}
    {{i}}
{% endfor %}

{# Outputs :
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
#}

但是, 你可以轻松防止此行为。 Twig允许你使用以下两种方法清除标签之间不必要的空间:

  • 在每个标签级别上控制空格。
  • {%spaceless%}标签。

在每个标签级别上控制空格, 允许你从打印的所有内容中删除空格。要使用它, 请在任何打印标签的前面和后面分别包含一个减号:

{% for i in 1..10 %}
    {# Note the - symbol at the beginning and the end of the print tag #}
    {{- i -}}
{% endfor %}

{# Outputs :
    12345678910
#}

请注意, 如果需要, 你可以只使用一侧, 而不能只使用两侧:

<li>    {{- "A string" }}    </li>

{# outputs '<li>no spaces    </li>' #}

<li>    {{ "A string" -}}    </li>

{# outputs '<li>    no spaces</li>' #}

尽管无空格标记允许你打印不带空格的HTML块(这提供了缩小效果):

{% spaceless %}
    <div>
        <strong>Hey, no easy readable HTML</strong>
    </div>
{% endspaceless %}

{# output will be <div><strong>Hey, no easy readable HTML</strong></div> #}

4.用细枝漂亮地打印一个JSON编码的数组

Twig使用常量方法支持常量。

在PHP中, 你可以使用JSON_PRETTY_PRINT常量作为json_encode函数的参数来漂亮地打印json字符串。

<?php

$json_string = json_encode($data, JSON_PRETTY_PRINT);

Twig在后台使用json_encode, 因此你仍然需要使用常量:

{% set data = {
    "Hey": "Ho", "What": 12, "Value" : true
}%}

{{ data|json_encode()|raw }}

{{ data|json_encode(constant('JSON_PRETTY_PRINT'))}}

{#Outputs :
{# If HTML symbols appears, use the |raw filter after the json_encode function #}

{"Hey":"Ho", "What":12, "Value":true}

{
    "Hey": "Ho", "What": 12, "Value": true
}
#}

3.修改日期

使用Twig, 你可以像使用PHP中的DateTime对象一样轻松地修改日期。

<?php
$date = new DateTime('2000-12-31');

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
//2001-01-31

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
//2001-03-03
?>

date_modify过滤器使用给定的修饰符字符串修改日期:

{{ "now"|date_modify('+1 month')|date('Y-m-d')}}

2.限制字符串长度

在很多情况下, 你都希望截断字符串以防止发生不必要的行为。要使用默认长度剪切字符串, 请使用切片过滤器。

{% set myTextVariable = "A semi long string"%}

{{myTextVariable|slice(0, 10)}}
{# Outputs : A semi lon #}

你可以使用三元运算符来限制文本的长度并放置三个点:

{% set myTextVariable = "A semi long string"%}

{# If the string length > 50, then cut it and append 3 dots .... | otherwise just print the text.#}
{{ myTextVariable|length > 50 ? myTextVariable|slice(0, 10) ~ '...' : myTextVariable }}

{# Which is the same as : #}
{% if myTextVariable|length > 50 %}
    {{ myTextVariable|slice(0, 10) ~ '...'}}
{% else %}
    {{ myTextVariable }}
{% endif %}

1.使用宏

宏可与常规编程语言中的功能媲美。它们对于将常用的HTML习惯用法放入可重用的元素中而不重复你自己很有用。

从理论上讲:是一种自写的树枝函数, 根据收到的参数输出自定义html。

宏的最佳做法是将其放置在另一个树枝文件中, 并使用import标记将其包含在当前文件中:

{% import "forms.html" as forms %}

但是, 你可以在任何位置添加宏。如果决定将它们添加到工作所在的同一文件中, 则只需要_self路径:

{% import _self as forms %}

我们可以使用宏将重复的html块作为表单打印。在下面的示例中, 我们将使用一个简单的宏来打印引导注册表格:

{% macro input(name, value, type, size) %}
    <div class="form-group">
        <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
    </div>
{% endmacro %}

{% import _self as forms %}

<form action="register.php" method="post">
    {{forms.input("frm_username", null, "text")}}
    {{forms.input("frm_password", null, "password")}}
    {{forms.input("frm_email", null, "email")}}
    {{forms.input("frm_birthday", null, "date")}}
    {{forms.input("frm_submit", "Register", "submit")}}
</form>

输出应该类似于:

<form action="register.php" method="post">
        <div class="form-group">
        <input type="text" name="frm_username" value="" size="20" />
    </div>

        <div class="form-group">
        <input type="password" name="frm_password" value="" size="20" />
    </div>

        <div class="form-group">
        <input type="email" name="frm_email" value="" size="20" />
    </div>

        <div class="form-group">
        <input type="date" name="frm_birthday" value="" size="20" />
    </div>

        <div class="form-group">
        <input type="submit" name="frm_submit" value="Register" size="20" />
    </div>

</form>

你可以在以下小提琴中看到一个有效的宏:

常见问题解答

如何在Twig中连接字符串

在PHP中, 我们曾经使用来连接字符串。 (点)符号。在Twig中, 我们将使用〜(波浪号)符号来连接字符串。

{{"Hello " ~ app.user.username ~ " how are you today?"}}

你也可以使用第9点中提到的字符串插值。

如何检查变量是否存在

根据你的Twig环境的配置, 你可能需要检查是否存在变量以防止错误。

要检查变量是否存在, 请使用is define语句。

{# Uncomment to print the content inside the twig statement
    {% set variable = 12 %}
#}

{% if variable is defined %}
    {{- "Variable exists :" ~ variable -}}
{% endif%}

如何检查字符串或数组是否包含值

要检查元素是否在数组内, 可以使用in语句。

{% set mytext = "hello how are you today" %}

{% set myarray = ["Hello", 12, 15, "other string"] %}

{% if "hello" in mytext %}
    {{"'hello' has been found in the string"}}
{% endif %}

{% if "Hello" or 12 in myarray %}
    {{"15 or hello found in array"}}
{% endif %}

额外

你可以在twigfiddle.com上在线测试你的Twig代码片段, 这比在本地创建Twig环境更快, 更容易访问并且更快。

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 每个开发人员都应了解的10条Twig技巧和基本功能

评论 抢沙发

评论前必须登录!