Twig模板引擎使用笔记

合集下载

Twig总结

Twig总结

定界符1、{% ... %} 用来执行语句,比如for循环、IF判断、过滤等操作2、{{ .... }} 用来显示变量可以符号== != < > >= <= + - ~ * / // % ** | [] . .. and or not in is b-and b-or b-xor部分符号的含义如下~ :连接两字符串,相当于PHP 中的点号//:整除**:乘方,相当于PHP 中的^b-and、b-or、b-xor:按位与、按位或、按位异或-:减法以及去除空白的简写用法,如{{- 数据}} => 去除左边的空白、{{ 数据-}} => 去除右边的空白、{{- 数据-}} => 去除两边的空白注释{# This is Twig Comment #}快捷方式:ctrl + shift + /变量程序会传递给模板若干变量,你需要在模板里输出他们。

例如输出$hello {{ hello }}如果传递给模板的是对象或者数组,你可以使用点. 来输出对象的属性或者方法,或者数组的成员。

或者你可以使用下标的方式。

{{ foo.bar }}{{ foo['bar'] }}如果你访问的值不存在就会返回null。

TWIG有一整套的流程来确认值是否存在。

for.bar会进行以下操作。

如果 foo是个数组,就尝试返回bar成员,如果不存在的话,往下继续。

如果foo是个对象,会尝试返回bar属性,如果不存在的话,往下继续。

会尝试运行bar方法,如果不存在的话,往下继续。

会尝试运行getBar方法,如果不存在的话,往下继续。

会尝试运行isBar方法,如果不存在的话,返回null全局变量∙_self 这个参看macro标签∙_context 这个就是当前的环境∙_charset: 当前的字符编码变量赋值∙ {% set foo = 'foo' %}∙ {% set foo = [1, 2] %}∙ {% set foo = {'foo': 'bar'} %}数组遍历-- 按数组value遍历:{% for value in foo %}{{ value }}{% endfor %}-- 按数组key遍历:{% for key in foo|keys %}{{ key }}{% endfor %}-- 按key,value遍历{% for key, value in foo %}{{ key}}:{{value }}{% endfor %}-- 如果 foo 非数组,还可以使用else语句,如:{% for key, value in foo %}{{ key}}:{{value }}{% else %}foo is Not a Array{% endfor %}-- 也可以直接带条件,遍历二维数组时比较有用,可用value.field来判{% for key, value in foo if value == 1%}{{ key}}:{{value }}{% endfor %}循环体内部变量:loop.index 循环的次数(从1开始)loop.index0 循环的次数(从0开始)loop.revindex 循环剩余次数(最小值为1)loop.revindex0 循环剩余次数(最小值为0)loop.first 当第一次循环的时候返回truest 当最后一次循环的时候返回trueloop.length 循环的总数loop.parent 被循环的数组过滤器变量可以通过过滤器进行修改。

java模板引擎哪个好

java模板引擎哪个好

java模板引擎哪个好在Java开发中,常常需要使用模板引擎来实现动态模板的渲染,从而实现页面的生成、文本文件的生成等功能。

目前市面上有很多优秀的Java模板引擎,下面介绍几种常用的Java模板引擎,以供参考。

1. FreeMarkerFreeMarker是常用的Java模板引擎之一,它以简单的语法和高效的性能而著称。

它支持多种数据源,包括POJO、Map和XML 等,同时也支持一些高级特性,如模板继承、条件判断等。

与其他模板引擎不同,FreeMarker只提供模板渲染功能,不涉及到应用框架和业务逻辑。

由于其性能出众和易用性,FreeMarker在企业级Web应用开发中得到广泛应用。

2. VelocityVelocity是一个轻量级的模板引擎,它来自于Apache软件基金会。

Velocity具有简单实用的语法,易于入门。

它支持多种模板格式,包括HTML、XML和JSON等,同时还支持模板继承和条件判断等特性。

与其他模板引擎不同,Velocity具有较强的可扩展性,可以通过插件机制扩展模板引擎的功能。

3. ThymeleafThymeleaf是一个现代化的服务器端Java模板引擎,它通过自然语言的语法来处理模板,并且允许使用HTML、XML、JavaScript等格式的模板。

Thymeleaf不只是一个静态页面渲染引擎,它还可以轻松地集成到SpringMVC等Web框架中,实现动态模板的渲染和数据绑定等功能。

Thymeleaf还可以处理国际化、表单处理、格式化、URL处理等特性,具有很强的可扩展性。

4. JtwigJtwig是一个快速而灵活的Java模板引擎,它支持多种数据源,包括Map、POJO和Spring框架中的Bean等。

Jtwig同样支持模板继承、条件判断、循环迭代等特性,同时还提供了丰富的标签和过滤器,支持自定义标签和过滤器的扩展。

Jtwig提供了丰富的模板格式,包括HTML、XML、JSON和Markdown等。

分布式xml twig查询处理方法

分布式xml twig查询处理方法

分布式xml twig查询处理方法
Twig是一种处理XML的非常有用的工具,在分布式网络管理中尤其有用。

XML可以被用于包含任何类型的信息,因此可以与Twig一起将数据分布在网络中。

Twig使用文本文件格式来存储XML文档,允许任何系统发布、订阅和查询数据库。

由于这些文件与XML文档一起存储,可以从网络中的任何计算机访问这些文件。

Twig有两种不同的查询处理方法。

第一种是XPath,它可以用于在XML文档中查找模式。

XPath不仅支持基本查询,还支持复杂查询,允许按字符串匹配、节点层次结构查找和复杂逻辑检索条件把XML文档中特定元素筛选出来。

另一种查询处理方法是XQuery,XQuery采用从李文蜀至XPath的新术语和功能,允许更灵活地操作XML文档,如搜索、对比、计算和生成XML文档的结构。

XQuery提供的元素模糊搜索,允许探测关联数据,并允许编写类似SQL查询的XML文档。

Twig还支持搜索,它允许开发人员搜索XML文档中的元素,也可以在节点之间以及根节点和子节点之间设置逻辑“等于”、“不等于”等条件。

层次查询允许查找特定的结构数据的子和孙节点,以及按字符串前缀或正则表达式查询节点名称和属性,从而提供一个更灵活的查询处理模型。

可以看出,Twig支持的XPath、XQuery和搜索查询语言,可以使XML在分布式网络管理中被有效地使用。

通过Twig对XML文档的查询处理,开发人员可以轻松地实现数据发布、订阅和查询,使其能够有效地应用于分布式环境中。

此外,Twig还提供了处理XML文档所需的函数和操作,使其在网络设计中更具有效率性。

如何使用Symfony进行前端开发

如何使用Symfony进行前端开发

如何使用Symfony进行前端开发Symfony是一种开源的PHP框架,被广泛应用于Web应用程序的开发。

虽然Symfony主要用于后端开发,但它也提供了一些有用的工具和功能,可以帮助我们进行前端开发。

本文将介绍如何使用Symfony进行前端开发。

一、使用Twig模板引擎Twig是Symfony内置的模板引擎,它相比其他模板引擎更加简洁、易用。

我们可以在Symfony项目的视图层中使用Twig来进行前端开发。

1. 安装Twig首先,我们需要在Symfony项目中安装Twig。

在终端中运行下面的命令:```composer require twig```2. 创建Twig模板在Symfony项目的`templates`文件夹下创建一个新的Twig模板文件,例如`index.html.twig`。

在模板中,我们可以使用Twig提供的模板语法来渲染数据。

3. 使用Twig模板使用Twig模板时,我们可以通过控制器将数据传递给模板。

在控制器中,我们调用Twig的`render()`方法来渲染Twig模板,并可以传递数据。

例如:```phpuse Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\Routing\Annotation\Route;class MyController extends AbstractController{/*** @Route("/", name="homepage")*/public function index(){$data = ['title' => 'Welcome to my website','content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' ];return $this->render('index.html.twig', $data);}}```在Twig模板中,我们可以使用`{{ }}`来输出变量。

twig模板常用语法

twig模板常用语法

twig模板常用语法
"Twig模板常用语法" 指的是在使用Twig模板引擎时,经常使用或非常有用的语法和特性。

Twig是一个用PHP编写的模板引擎,用于Web开发。

以下是Twig模板的一些常用语法:
1.变量插值:使用{{ variable }}语法将变量插入到模板中。

2.输出标签:使用{{ }}标签将内容输出到模板中。

3.控制结构:使用条件语句、循环语句等控制结构来控制模板的渲染。

4.过滤器:使用管道符号|对变量进行过滤和格式化。

5.函数:使用函数对变量进行处理和操作。

6.继承:使用继承来共享模板的布局和样式。

7.包含:使用{% include %}指令将其他模板包含到当前模板中。

8.注释:使用注释对模板进行注释和说明。

9.宏:使用宏定义可重用的模板片段。

10.运算符:支持常见的算术运算符、比较运算符和逻辑运算符等。

总结来说,"Twig模板常用语法"是指在使用Twig模板引擎时,经常使用或非常有用的语法和特性。

这些语法可以帮助开发者更方便地构建动态网页和网站,提高开发效率。

twig模版学习心得

twig模版学习心得

Twig入门今天学习了下twig模版,感觉还挺好用的,这里就把我学习过程中的一些心得分享出来!第一步是安装twig:那么如何安装twig呢,比较快捷的方法是利用composer进行安装,如果不懂composer的话,我就先说下如何安装composer吧:Composer的安装分为两种情况,Windows环境和linux环境:Linux环境下比较简单,命令行模式下,进入你需要安装composer的项目目录下,运行以下代码Curl -s https:///installer | phpWindows环境下比较麻烦,直接给传送门吧,/article/4f34706ed04013e386b56d72.html安装好composer之后,在项目目录下新建一个名为composer.json的文件,用文本编辑器打开composer.json,输入以下内容:{"require": {"twig/twig": "1.*"}}保存后,在项目目录下,运行以下命令:php composer.phar install这样twig的安装就完成了!第二步是使用twig首先指定twig模版放置的目录('templates'就是模版放置的目录,这个目录需要自己创建,所有的html文件都放在这个目录下)$loader = new Twig_Loader_Filesystem('templates');然后创建twig对象$twig = new Twig_Environment($loader, array(//'cache' => '/compilation_cache', //选项有很多设置,这里就不多做赘述了));有了对象之后,调用render方法对模版进行渲染echo $twig->render("index.html",array('name' => ‘name’));//name是传入index.html的参数,index.html这个文件是template中的模版附上php的源代码(另放在template目录下的模版可以是任意的html文件):<?phprequire 'vendor/autoload.php';$loader = new Twig_Loader_Filesystem('templates');$twig = new Twig_Environment($loader, array(//'cache' => '/compilation_cache',));$name = "name";echo $twig->render("index.html",array('name' => $name));?>第三步是了解twig的一些tag这里容我偷个懒,给个传送门吧/jiaochangyun/article/details/7178372出自jiaochangyun的博客,我觉得写的很详细,希望能对大家有所帮助!。

Twig模板引擎用法入门教程

Twig模板引擎⽤法⼊门教程本⽂实例讲述了Twig模板引擎⽤法。

分享给⼤家供⼤家参考,具体如下:介绍Twig是⼀个灵活、⾼效并且安全的PHP模板引擎。

如果你使⽤过Smarty、Django或者Jinja这类基于⽂本的模板引擎的话,那么你会觉得Twig是很⾃然⽽然的事情。

Twig严格遵守了PHP的信念,同时增加了在模板环境中很有⽤的函数,这些做法使得Twig不论是对设计师还是开发⼈员,都是⾮常友好的。

Twig的主要特征有:⾼效:Twig将模板编译成了优化了的PHP⽂件,与原⽣的PHP代码⽐较⽽⾔,性能损耗⾮常⼩。

安全:Twig使⽤沙箱(sandbox)模式去运⾏模板中不被信任的代码。

这使得我们可以选择Twig作为那些允许⽤户修改模板的应⽤的模板引擎。

灵活:Twig具有灵活的语法分析器和语法解析器,它允许开发⼈员定义⾃⼰的标签(tags)和过滤器(filters),并且创建⾃⼰的领域特定语⾔(DSL,domain specific language)。

必要条件Twig需要的最低PHP版本为5.2.4。

安装安装Twig有多种⽅法。

如果你不能确定使⽤哪⼀种,那么直接下载压缩包即可。

压缩包安装从下载页⾯下载最新的压缩包解压将解压出来的⽂件放置到项⽬可以访问到的地⽅。

安装开发版本安装Subversion或者Git使⽤PEAR包安装安装PEARpearinstalltwig/Twig (或者pearinstalltwig/Twig-beta)基础API⽤法本节将给出⼀个Twig的PHP API的简单介绍使⽤Twig的第⼀步是注册它的autoloader:require_once '/path/to/lib/Twig/Autoloader.php';Twig_Autoloader::register();记得⽤Twig所在路径代替/path/to/lib注:Twig在类的命名上遵守PEAR的约定,这意味着你可以在⾃⼰编写的autoloader中整合对Twig的类的加载。

twig 遍历数组 追加分隔符

twig 遍历数组追加分隔符
Twig模板引擎是一种流行的模板引擎,广泛用于PHP应用程序的视图层。

在Twig中,遍历数组是很常见的任务,但是有时我们需要在数组元素之间添加分隔符。

本文将介绍如何在Twig中遍历数组并添加分隔符。

首先,让我们看一下如何在Twig中遍历数组。

假设我们有一个名为“items”的数组,我们可以使用Twig的for循环来遍历它: ```twig
{% for item in items %}
{{ item }}
{% endfor %}
```
这个循环将输出数组中的每个元素。

但是,如果我们想在元素之间添加分隔符,该怎么办呢?让我们假设我们想要在每个元素之间添加逗号。

我们可以使用Twig的loop变量来检测当前元素是否是最后一个,并根据情况添加逗号:
```twig
{% for item in items %}
{{ item }}
{% if not st %},{% endif %}
{% endfor %}
```
在这个例子中,我们使用了loop变量的“last”属性,该属性是一个布尔值,表示当前元素是否是数组中的最后一个元素。

如果不是最后一个元素,我们就添加逗号。

否则,我们不添加任何东西。

这种方法可以很容易地适应其他类型的分隔符,例如空格、管道符等。

只需要将逗号更改为所需的分隔符即可。

总之,在Twig中遍历数组并添加分隔符是一项有用的任务,它可以使我们的模板更加灵活和易于维护。

我们可以使用Twig的
for循环和loop变量来轻松实现这一点。

模板渲染的基本原理解析

模板渲染的基本原理解析模板渲染在现代程序开发中扮演着重要的角色,它是将动态数据和静态模板进行结合,生成最终呈现给用户的界面。

在本文中,我们将深入探讨模板渲染的基本原理,并介绍几种常见的模板引擎。

一、什么是模板渲染模板渲染是一种将数据和模板进行结合的技术,它的目标是生成用户最终看到的网页、邮件、文档等输出。

在传统的开发模式中,开发人员通常需要手动拼接字符串将数据插入到静态模板中。

这种方式会导致代码冗长、难以维护和管理。

而采用模板渲染的方式,我们可以将数据和模板进行分离,使得开发工作更加高效和可维护。

二、模板渲染的基本原理模板渲染的基本原理是将模板中的变量替换为实际的数据。

为了实现这一过程,模板渲染通常有以下几个关键步骤:1. 解析模板:模板渲染引擎首先会对模板进行解析,识别出其中的标记和变量。

标记通常用于控制流程和条件判断,而变量则代表动态数据。

2. 数据填充:在模板解析完成后,引擎会将解析得到的标记和变量替换为实际的数据。

这一过程可以通过正则表达式、解析树等方式实现。

3. 生成输出:渲染引擎根据数据填充的结果生成最终的输出。

这一输出可以是HTML、文本文件、JSON等格式,根据具体应用场景而定。

三、常见的模板引擎1. Jinja2:Jinja2是一个基于Python的模板引擎,它使用简洁的语法和强大的功能,广泛应用于Web开发领域。

Jinja2支持模板继承、条件判断、循环等高级特性,提供了丰富的过滤器和扩展机制。

2. Handlebars:Handlebars是一个跨平台的JavaScript模板引擎,它采用Mustache语法,简洁易懂。

Handlebars支持条件判断、循环和子模板等功能,可以与多种前端框架无缝集成。

3. Twig:Twig是一个PHP模板引擎,它由Symfony框架开发团队负责维护。

Twig拥有高性能和安全性,支持模板继承、自定义函数和过滤器等功能,是PHP开发中首选的模板引擎之一。

Twig 模板引擎用户指南说明书

Table of ContentsAbout1 Chapter 1: Getting started with twig2 Remarks2 Examples2 Basic API Usage2 What is Twig?3 Introduction4 Chapter 2: Advanced usage6 Remarks6 Examples6 Building the C Extension6 Chapter 3: Basic template syntax7 Introduction7 Examples7 Accessing variables7 Accessing array elements7 Accessing object properties7 Filters8 Conditional blocks8 For Loop9 Ternary Operator (Shorthand If-Then-Else) & Null-Coalescing Operator9 The ternary operator (?:)9 The null-coalescing operator (??:)10 Whitespace handling10 Chapter 4: Extending twig12 Remarks12 Examples12 Adding custom filters/functions12 Creating a Twig_Extension12 Simple Date of Birth to age filter13Chapter 5: Template inheritance15 Examples15 Using a base template15 base.twig.html15 Change the content of an included template15 article.twig.html16 articles.twig.html16 Variable inheritance16 parent.html.twig16 child.html.twig16 Comparison of Include, Extends, Use, Macro, Embed16 Include17 Extends17 Use17 Macro18 Embed18 Credits21AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: twigIt is an unofficial and free twig ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official twig.The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to ********************Chapter 1: Getting started with twigRemarksThis section provides an overview of what twig is, and why a developer might want to use it.It should also mention any large subjects within twig, and link out to the related topics. Since the Documentation for twig is new, you may need to create initial versions of those related topics. ExamplesBasic API UsageIt can also be installed by downloading the source code and placing it in a directory of your project. However there are many benefits to using composer.require '/path/to/lib/Twig/Autoloader.php';Twig_Autoloader::register();$loader = new Twig_Loader_Filesystem('/path/to/templates');$options = array('strict_variables' => false,'debug' => false,'cache'=> false);$twig = new Twig_Environment($loader, $options);When creating a new Twig_Environment instance, you can pass an array of options as the constructor's second argument. Here is a list of the available options:•debug (boolean, default false)When set to true, the generated templates have a __toString() method that you canuse to display the generated nodes.•charset (string, default utf-8)The charset used by the templates.•base_template_class (string, default Twig_Template)The base template class to use for generated templates.cache (string or false, default false)•An absolute path where to store the compiled templates, or false to disable caching(which is the default).auto_reload (boolean, default inherited from debug)•When developing with Twig, it's useful to recompile the template whenever the sourcecode changes. If you don't provide a value for the auto_reload option, it will bedetermined automatically based on the debug value.strict_variables (boolean, default false)•If set to false, Twig will silently ignore invalid variables (variables and orattributes/methods that do not exist) and replace them with a null value. When set totrue, Twig throws an exception instead.autoescape (string or boolean, default true)•If set to true, HTML auto-escaping will be enabled by default for all templates.As of Twig 1.8, you can set the escaping strategy to use (html, js, false to disable).As of Twig 1.9, you can set the escaping strategy to use (css, url, html_attr, or a PHPcallback that takes the template "filename" and must return the escaping strategy touse -- the callback cannot be a function name to avoid collision with built-in escapingstrategies).As of Twig 1.17, the filename escaping strategy determines the escaping strategy touse for a template based on the template filename extension (this strategy does notincur any overhead at runtime as auto-escaping is done at compilation time.)optimizations (integer, default -1)•A flag that indicates which optimizations to apply:set to -1 to enabled all optimalizationsset o 0 to disable all optimalitazationsOfficial Twig Installation GuideA Twig PHP extension (written in C) can also be compiled and installed, and the PHP package will automatically take advantage of that for optimizing some common routines.What is Twig?Twig is a templating language that compiles to optimized PHP code. It is primarily used for outputting HTML, but can also be used to output any other text-based format. It is a standalone component that can be easily integrated into any PHP project.It provides many excellent features:•Autoescaping for HTML (helps to prevent XSS)•Syntax designed with templating in mind (based on Django templates)Template inheritance••MacrosOfficial Twig Templating DocumentationExample of Twig's syntax:{% extends "base.html" %}{% block sidebar %}{{ parent() }}<span>Sidebar content specific to this page</span>{% endblock sidebar %}{% block body %}<p>Select an item:</p><ul>{% for item in list %}<li><a href="/items/{{ item.id }}">{{ }}</a>{% else %}<li>No items yet.{% endfor %}</ul>{% endblock body %}IntroductionIf you have any exposure to other text-based template languages, such as Smarty, Django, or Jinja, you should feel right at home with Twig. It's both designer and developer friendly by sticking to PHP's principles and adding functionality useful for templating environments.The key-features are...•Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to •be used as a template language for applications where users may modify the templatedesign.•Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define their own custom tags and filters, and to create their own DSL.Twig is used by many Open-Source projects like Symfony, Drupal, eZPublish and many frameworks have support for it as well like Slim, Yii, Laravel, Codeigniter,silex and Kohana — just to name a few.InstallationThe recommended way to install Twig is via Composer:For php 5.x userscomposer require "twig/twig:~1.0"For php 7.x userscomposer require "twig/twig:~2.0"Read Getting started with twig online: https:///twig/topic/1100/getting-started-with-twigChapter 2: Advanced usageRemarksPlease note that the Twig extension is not compatible with PHP7 and although there is a pull request to resolve this situation it was not yet made part of version 1.x. With the most recent Twig 2.x release the C extension was removed but might be part of 2.1. Some benchmarks reveal minimal improvements with the C extension under PHP7.ExamplesBuilding the C ExtensionThe C extension is an optional feature of Twig that offers some performance improvements of template rendering. The source code for the extension is located in the Twig source code directory at ext/twig. It compiles like any other PHP extentension:cd ext/twigphpize./configuremakemake installEnable the extension in the php.ini file. Once the extension is installed, Twig will automatically detect and use it at runtime.Read Advanced usage online: https:///twig/topic/8696/advanced-usageChapter 3: Basic template syntaxIntroductionExplanation of basic template syntax constructsExamplesAccessing variablesIn Twig templates variables can be accessed using double curly braces notation {{ variableName }}.Basic example of greeting user<!DOCTYPE html><html><body><span>Hello {{ name }}</span></body></html>Accessing array elementsTwig as a parameter can receive array. To access a specific element of array you can use regular php array access bracket notation {{ array[key] }}.Previous example modified to use array as a parameter<!DOCTYPE html><html><body><span>Hello {{ user['name'] }}</span></body></html>Accessing object propertiesObjects also can be passed as a parameter to template. 'Dot' (.) notation is used to access specific object properties {{ object.propertyName }}.Same example with object as a parameter<!DOCTYPE html><html><body><span>Hello {{ }}</span></body></html>FiltersVariables can be modified using filters. To apply filter to variable follow variable name with pipe | and filter name:{{ variable|filterName }}For example to display variable value in uppercase use construct.{{ variable|upper }}Filters can be parametrized. Filter parameters are passed inside parentheses as a comma(,) separated list :{{ variable|filterName(param1, param2, ...) }}To round number to given precision we can use filter round, it accepts up to 2 parameters. First one specifies precision (default: 0), second one rounding method (default: common).To round number to 1 decimal place using common method you can use {{ number|round(1,'common') }} or {{ number|round(1) }} as common is default method.Filters can also be used on embedded objects & array variables:{{ array['key'] | upper }} {{ object.text | upper }}Filters can also be concatenated:{% set array = "3,1,2"|split(',') %}{{ array | sort | first }}List of basic filters is available hereConditional blocksParts of template can be displayed conditionally. If statement is used for this purpose. It's similar to if statement in programing languages. Contents of block are executed/displayed if an expression evaluates to true.{% if enabled == false %}Disabled{% endif %}Disabled will be displayed only when enabled will be equal false.Multiple branches can be created using elseif and else.{% if temperature < 10 %}It's cold{% elseif temperature < 18 %}It's chilly{% elseif temperature < 24 %}It's warm{% elseif temperature < 32 %}It's hot{% else %}It's very hot{% endif %}For LoopFor loops can be really useful in TWIG, allowing the creation of data-dynamic web pages.Say we create a simple array of numbers:{% set array = "3,1,2" %}We can then iterate over the array and print out whatever we want. Any data within the array block will be outputted in relation to the amount of data within the array. This example would print out three h1 elements with the array data concatenated.{% for current in array %}<h1>This is number {{ current }} in the array </h1>{% endear %}Note that {{ current }} was used to access the data and not a version of arraySee this working: https:///mxwkea/2A further example of this could be using objects. For example, say we have an Entity object with the field 'name' along with its relevant getters and setters. If a number of these entities are also stored within the Array, they can be accessed like any other Objects within TWIG:{% for currentObject in ArrayOfObjects %}{{ }}{% endfor %}See this working with JSON data: https:///mxwkeaTernary Operator (Shorthand If-Then-Else) & Null-Coalescing OperatorThe ternary operator (:)Support for the extended ternary operator was added in Twig 1.12.0.{{ foo ? 'yes' : 'no' }}Evaluates:if foo echo yes else echo no{{ foo ?: 'no' }}or{{ foo ? foo : 'no' }}Evaluates:if foo echo it, else echo no{{ foo ? 'yes' }}or{{ foo ? 'yes' : '' }}Evaluates:if foo echo yes else echo nothingThe null-coalescing operator (:){{ foo ?? 'no' }}Evaluates:Returns the value of foo if it is defined and not null, no otherwiseWhitespace handlingTo remove whitespace (spaces, tabs, newlines…) between HTML tags use spaceless tag: {% spaceless %}<div><span>foo bar </span></div>{% endspaceless %}{# produces output <div><strong>foo bar </strong></div> #}If you need to remove whitespace on a per tag level, use whitespace control modifier i.e. hyphen (-). Using it, you can trim leading and or trailing whitespace:{% set value = 'foo bar' %}<span> {{- value }} </span>{# produces '<span>foo bar </span>' #}<span> {{ value -}} </span>{# produces '<span> foo bar</span>' #}<span> {{- value -}} </span>{# produces '<span>foo bar</span>' #}<span {%- if true %} class="foo"{% endif %}>{# produces '<span class="foo">' #}<span {%- if false %} class="foo"{% endif %}>{# produces '<span>' #}Read Basic template syntax online: https:///twig/topic/8697/basic-template-syntaxChapter 4: Extending twigRemarksTwig already has some built-in filters and functions, but what if the built-in features are lacking or you have to access some default PHP functions in a templateExamplesAdding custom filters/functionsHere are some example on how to add new filters/functions to twig,the synax for adding Twig_Function s are the same as the Twig_Filter ones, just change the keywords accordingly<?php$twig = new Twig_Environment($loader);/* You can chain a global function */$twig->addFilter(new Twig_SimpleFilter('floor', 'floor'));/* You can specify a custom function */$twig->addFilter(new Twig_SimpleFilter('money', function($value, $currency, $prefix = false, $decimals = 2, $dec_point = "." , $thousands_sep = ",") {$value = number_format($value, $decimals, $dec_point, $thousands_sep);if ($prefix) return $currency.' '.$value;return $value.' '.$prefix;});/* You can chain an object's method */$twig->addFilter(new Twig_SimpleFilter('foo_bar', array($foo, 'bar')));Creating a Twig_ExtensionYou can group all your custom functions/filters/tests/... inside a custom Twig_Extension class: ProjectTwigExtensionclass ProjectTwigExtension extends Twig_Extension {public function getFunctions() {return array(new Twig_SimpleFunction('twig_function_name', array($this,'getTwigFunctionName')),new Twig_SimpleFunction('twig_function_foo', array($this, 'getTwigFunctionFoo')), );}public function getFilters() {return array(new Twig_SimpleFilter('twig_filter_name' , array($this, 'getTwigFilterName')), new Twig_SimpleFilter('twig_filter_foo' , array($this, 'getTwigFilterFoo')),);}public function getName() {return 'ProjectTwigExtension';}}Register extension in twig$twig = new Twig_Environment($loader);$twig->addExtension(new ProjectTwigExtension());More options can be found on the official docsSimple Date of Birth to age filterHow to ...1 - use twig extension class that extendsuse \Twig_Extensionclass dobToAge extends \Twig_Extension {2 - Add the appropriate filter by overriding getFilters() methodpublic function getFilters() {return array('age' => new \Twig_Filter_Method($this, 'getAge'),);}3 - Add some logic to get the age of a given Date of Birthpublic function getAge($date){if (!$date instanceof \DateTime) {// turn $date into a valid \DateTime object or let returnreturn null;}$referenceDate = date('01-01-Y');$referenceDateTimeObject = new \DateTime($referenceDate);$diff = $referenceDateTimeObject->diff($date);return $diff->y;}}Then, call your filter as follow,{{ yourDateOfBirthInstance | age }}Read Extending twig online: https:///twig/topic/4923/extending-twigChapter 5: Template inheritance ExamplesUsing a base templatebase.twig.html<!DOCTYPE html><html><head><title>{{ title | default('Hello World') }}</title><link rel="stylesheet" type="text/css" href="theme.css"> {% block css %}{% endblock %}</head><body>{% block body %}<nav>{% block navigation %}<a href="#">Link</a><a href="#">Link</a><a href="#">Link</a>{% endblock navigation %}</nav><section id="container"><section id="content">{% block content %}<p>Lorem ipsum dolor sit amet.</p></section>{% endblock content %}</section>{% endblock body %}</body></html>page.twig.html{% extends base.twig.html %}{% block navigation %}<a href="page2.html">Page 2</a><a href="page3.html">Page 3</a><a href="page4.html">Page 4</a>{% endblock %}{% block content %}This is my first page{% endblock content %}Change the content of an included templatearticle.twig.html<article><h1>{{ article.title }}</h1>{% block content %}<p>{{ article.content }}</p>{% endblock %}</article>articles.twig.html{# use default template for article #}{% for article in articles %}{% include "article.twig.html" %}{% endfor %}{# use custom template for article #}{% for article in articles %}{% embed "article.twig.html" %}{% block content %}<img src="{{ article.image }}" alt="{{ article.title }}" /> {{ parent() }}{% endblock %}{% endembed %}{% endfor %}Variable inheritanceparent.html.twig<!DOCTYPE html><html><head><title>{{ title_variable | default('Normal Page') }}</title></head><body><h1>This is the {{ title_variable }} Page</h1></body></html>child.html.twig{% extends "parent.html.twig" %}{% set title_variable = "Child" %}Comparison of Include, Extends, Use, Macro, EmbedThere are various types of inheritance and code reuse in Twig:IncludeThe main goal is code reuse. Consider using header.html.twig & footer.html.twig inside base.html.twig as an example.header.html.twig<nav><div>Homepage</div><div>About</div></nav>base.html.twig{% include 'header.html.twig' %}<main>{% block main %}{% endblock %}</main>ExtendsThe main goal is vertical inheritance. Consider extending base.html.twig inside homepage.html.twig and about.html.twig as an example.base.html.twig{% include 'header.html.twig' %}<main>{% block main %}{% endblock %}</main>homepage.html.twig{% extends 'base.html.twig' %}{% block main %}<p>You are at the homepage</p>{% endblock %}about.html.twig{% extends 'base.html.twig' %}{% block main %}<p>You are at the about page</p>{% endblock %}UseThe main goal is horizontal reuse. Consider using sidebar.product.html.twig insidesingle.product.html.twig (extends yout.html.twig) and single.service.html.twig (extends 'yout.html.page') pages. (it's like macros, but for blocks)sidebar.html.twig<aside>{% block sidebar %}{% endblock %}</aside>single.product.html.twig{% extends 'yout.html.twig' %}{% use 'sidebar.html.twig' %}{% block main %}<p>You are at the product page for product number 123</p>{% endblock %}single.service.html.twig{% extends 'yout.html.twig' %}{% use 'sidebar.html.twig' %}{% block main %}<p>You are at the service page for service number 456</p>{% endblock %}MacroThe main goal is having reusable markup across many templates with variables. Consider a function which gets some variables and outputs some markup.form.html.twig{% macro input(name, value, type) %} <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" }}" /> {% endmacro %}profile.service.html.twig{% import "forms.html.twig" as forms %}<div>{{ forms.input('username') }}</div>EmbedThe main goal is block overriding. It has functionality of both Use & Include together. Consider embedding pagination.html.twig in product.table.html.twig & service.table.html.twig. pagination.html.twig<div><div>{% block first %}{% endblock %}</div>{% for i in (min + 1)..(max - 1) %}<div>{{ i }}</div>{% endfor %}<div>{% block last %}{% endblock %}</div></div>product.table.html.twig{% set min, max = 1, products.itemPerPage %}{% embed 'pagination.html.twig' %}{% block first %}First Product Page{% endblock %}{% block last %}Last Product Page{% endblock %}{% endembed %}service.table.html.twig{% set min, max = 1, services.itemPerPage %}{% embed 'pagination.html.twig' %}{% block first %}First Service Page{% endblock %}{% block last %}Last Service Page{% endblock %}{% endembed %}Please note that embedded file (pagination.html.twig here) has access to the current context (min, max variables here). Also you may pass extra variables to the embedded file:pagination.html.twig<p>{{ count }} items</p><div><div>{% block first %}{% endblock %}</div>{% for i in (min + 1)..(max - 1) %}<div>{{ i }}</div>{% endfor %}<div>{% block last %}{% endblock %}</div></div>product.table.html.twig{% set min, max = 1, products|length %}{% embed 'pagination.html.twig' with {'count': products|length } %}{% block first %}First Product Page{% endblock %}{% block last %}Last Product Page{% endblock %}{% endembed %}Read Template inheritance online: https:///twig/topic/2922/template-inheritanceCredits。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Twig模板引擎使用笔记安装配置1.新建一个目录 libs2.在该目录下新建文件 composer.json,往该文件写入以下内容:3.{4. "require": {5. "twig/twig": "1.*"6. }7.}8.在 libs 目录上执行 composer install 安装 Twig(前提是已安装 Composer 包管理器)9.在 libs 上级目录新建三个文件夹:templates、templates_c、web,其中 templates 用来存放模板文件,templates_c 用来存放编译缓存文件,web 用来存放 PHP 源文件10.在 libs 上级目录新建文件 MyTwig.php 公共文件,内容如下:11.// 引用 Composer 自动加载文件12.require_once dirname(__FILE__).'/libs/vendor/autoload.php';13.14.// 注册 Twig 加载器15.Twig_Autoloader::register();16.17.// 设置基本的配置项18.$loader = new Twig_Loader_Filesystem(dirname(__FILE__).'/templates');19.$twig = new Twig_Environment($loader, array(20. 'cache' => dirname(__FILE__).'/templates_c',21. 'auto_reload' => true22.));23.后续使用时,只需让 web 目录下的 PHP 文件引用该公共文件,且在 templates 目录下放置好对应的模板即可,引用公共文件的语句为:require_oncedirname(dirname(__FILE__)).'/MyTwig.php';24.基本的模板渲染语句:echo $twig->render('abc.html.twig', array('name' => 'Ruchee'));可用符号== != < > >= <= + - ~ * / // % ** | [] . .. and or not in is b-and b-or b-xor部分符号的含义如下∙~:连接两字符串,相当于 PHP 中的点号∙//:整除∙**:乘方,相当于 PHP 中的 ^∙b-and、b-or、b-xor:按位与、按位或、按位异或∙-:减法以及去除空白的简写用法,如 {{- 数据 }} => 去除左边的空白、{{ 数据 -}} => 去除右边的空白、{{- 数据 -}} => 去除两边的空白变量可使用 {% set 变量名=变量值 %} 声明变量,也可写成 {% set 变量名 %} 变量值 {% endset %}PHP 中非关联数组被映射成 [元素1, 元素2, ...],关联数组则被映射成 {键1: 值1, 键2: 值2, ...}数据统一用 foo.bar 的形式表示,如果 bar 是形如 my-name 的名字,则需写成 attribute(foo,'my-name'),下面是 Twig 对 foo.bar 的解析顺序:1.当成数组的元素 foo['bar']2.当成对象的属性 foo.bar3.当成对象的方法 foo.bar()4.调用对象的 get 方法 foo.getBar()5.调用对象的 is 方法 foo.isBar()6.以上都没匹配上则返回 null几个内建的全局变量∙_self:当前模板的引用∙_context:当前上下文的引用∙_charset:当前字符集设置的引用测试语句∙三元运算符。

如 {{ '' ? 'a' : 'b' }} => 'b'∙xxx is yyy∙xxx is not yyy控制结构∙{% if aaa %} xxx {% elseif bbb %} yyy {% else %} zzz:判断语句∙{% for %} xxx {% endfor %}:迭代变量∙{% do %}:没什么其他含义,{% do 1+2 %} 等同于 {{ 1+2 }}∙{% flush %}:刷新输出缓冲,等同于 flush∙{% include %}:包含模板∙{% extends %}:扩展模板∙{% embed %} xxx {% endembed %}:包含模板并扩展该模板的内容,相当于 include 和 extends 的结合体∙{% use %}:包含模板,近似于多重继承∙{% from aaa import bbb as ccc %}:从指定模板导入宏并设置别名∙{% macro %} xxx {% endmacro %}:定义宏以便多次调用,与定义 PHP 函数无异∙{% sandbox %} {% include xxx %} {% endsandbox %}:对导入的模板指定沙箱模式,只对 include 语句有效,只在沙箱模式已开启的情况下生效∙{% block xxx %} 或 {% block %} xxx {% endblock %}:定义代码块或覆盖代码块∙{% set xxx %} 或 {% set %} xxx {% endset %}:在模板内定义变量∙{% filter %} xxx {% endfilter %}:多行过滤器∙{% spaceless %} xxx {% endspaceless %}:去除 HTML 片段中的空格∙{% autoescape %} xxx {% endautoescape %}:将字符串安全地处理成合法的指定数据∙{% verbatim %} xxx {% endverbatim %}:阻止模板引擎的编译,是 raw 的新名字内建过滤器过滤器用来修饰数据,各过滤器可以用竖线分隔进行链式调用,用括号传递参数也可以将过滤器当成单独的函数来用,形式如下:{% filter 过滤器名 %}待处理的数据{% endfilter %}∙batch:将数组按指定的个数分割成更小的数组,可选的第二个参数用来在元素不够的情况下进行填充。

如 {{ [1, 2, 3, 4, 5]|batch(2, 'NoItem') }} => [[1, 2], [3, 4], [5, 'NoItem']] ∙date_modify:修改时间,常与 date 联用。

如 {{ ''|date_modify('+3 days')|date('Y-m-d') }} => 将当前时间加3天后显示∙default:当所修饰的数据不存在或为空时,提供默认值。

如 {{ ''|default('Ruchee') }} => 'Ruchee'∙escape:将字符串安全地处理成合法的指定数据,可简写为 e,支持多种转换模式,默认模式为html,其他可选模式有 html_attr、js、css、url∙first:返回数组的第一个元素或字符串的第一个字符。

如 {{ {a: 1, b: 2, c: 3}|first }} =>1∙last:返回数组的最后一个元素或字符串的最后一个字符。

如 {{ {a: 1, b: 2, c: 3}|last }} => 3∙replace:替换一个字符串中的指定内容。

如 {{ '%s1 love %s2'|replace({'%s1': 'Ruchee', '%s2': 'Vim'}) }} => 'Ruchee love Vim'∙raw:让数据在 autoescape 过滤器里失效借用自PHP自带函数的过滤器∙abs:取绝对值∙nl2br:将字符串里的 \n 替换成 <br/>∙join:将数组的各个元素按指定分隔符组成字符串∙sort:对数组排序∙trim:去除字符串首尾的指定字符,默认为空格∙date:格式化时间,可处理与 strtotime 兼容的字符串,或 DateTime/DateInterval 的实例,可选的第二个参数用于指定时区,如果所修饰的数据为空则默认为当前时间∙reverse:反转一个数组或字符串,在 array_reverse 的基础上增加了对字符串的处理∙slice:截取数组或字符串的一部分,在 array_slice 的基础上增加了对字符串的处理∙keys:将数组的全部键名提取成一个数组,等同于 array_keys∙merge:合并两数组,近似于 array_merge 。

如 {{ 数组1|merge(数组2) }}∙length:返回数组元素的个数或字符串的长度,等同于 count 和 strlen 的结合体∙capitalize:将字符串的首字母大写,等同于 ucfirst∙title:将字符串中每个单词的首字母大写,等同于 ucwords∙lower:将字符串所有字母全部变成小写,等同于 strtolower∙upper:将字符串所有字母全部变成大写,等同于 strtoupper∙split:将字符串分割成数组,等同于 str_split∙striptags:去除字符串中的 HTML/PHP 标记,等同于 strip_tags∙url_encode:编码链接字符串,等同于 urlencode∙json_encode:编码 JSON 格式,等同于 json_encode∙format:格式化一个字符串,近似于 printf 。

如 {{ 'My name is %s, and I love %s'|format('Ruchee', 'Vim') }} => 'My name is Ruchee, and I love Vim' ∙number_format:格式化数值,等同于 number_format∙convert_encoding:编码转换,第一个参数指定转换后的编码,第二个参数指定转换前的编码,近似于 iconv内建函数∙even:是否为偶数∙odd:是否为奇数∙empty:是否为空∙null:是否为 null∙defined:是否已定义∙sameas:目标变量与指定值是否指向的是内存中的同一个地址,使用形式 if 变量值 is sameas(指定值)∙divisibleby:目标数值是否能够被指定值整除,使用形式 if 目标数值 divisibleby(指定值),其中指定值不能为 0∙iterable:目标变量是否是数组或者是否可迭代,使用形式 if 变量值 is iterable∙attribute:动态获取变量属性值,两种使用形式为 attribute(数组, '元素名') 和attribute(对象, '方法名', 可选参数)∙block:重复引用指定代码块,如 {{ block('title') }}∙constant:从字符串或对象取得常量值∙cycle:循环显示一个数组的元素,调用形式为 cycle(数组, 一个循环变量)∙date:格式化时间∙dump:在开启调试模式的情况下显示详细的变量信息,等同于 var_dump∙include:包含其他模板文件∙parent:在覆盖代码片段时用于引用父片段的内容∙random:制造一个随机数∙range:返回一个指定区间的数组,可指定步长,Twig 使用 .. 作为其简用法,等同于 range ∙template_from_string:根据字符串加载模板date : 2013-07-09、2013-07-10、2013-07-11。

相关文档
最新文档