TWIG 模板设计 快速入门手册 中文
写了好几篇关于twig的东西。。居然还没写个快速入门之类的。现在就写
概要
twig 的模板就是普通的文本文件,也不需要特别的扩展名,.html .htm .twig 都可以。
模板内的 变量 和 表达式 会在运行的时候被解析替换,标签(tags)会来控制模板的逻辑
下面是个最小型的模板,用来说明一些基础的东西
My Webpage
{{ a_variable }}
My Webpage
{{ a_variable }}
里面包含两种符号 {% ... %} 和 {{ ... }} 第一种用来控制的比如for循环什么的,第二个是用来输出变量和表达式的
ide 支持
很多ide 都对twig进行高亮支持。大伙自己找需要的吧。
Textmate via the Twig bundle
Vim via the Jinja syntax plugin
Netbeans via the Twig syntax plugin
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
变量
程序会传递给模板若干变量,你需要在模板里输出他们。例如输出 $hello
{{ hello }}
{{ hello }}如果传递给模板的是对象或者数组,你可以使用点 . 来输出对象的属性或者方法,或者数组的成员。或者你可以使用下标的方式。
{{ foo.bar }}
{{ foo['bar'] }}
{{ 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标签
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
过滤器 Firters
变量可以被过滤器修饰。过滤器和变量用(|)分割开。过滤器也是可以有参数的。过滤器也可以被多重使用。
下面这例子就使用了两个过滤器。
{{ name|striptags|title }}
{{ name|striptags|title }}striptas表示去除html标签,title表示每个单词的首字母大写。更多过滤器参见我博客
过滤器也可以用在代码块中,参见 filter标签
{% filter upper %}
This text becomes uppercase
{% endfilter %}
{% filter upper %}
This text becomes uppercase
{% endfilter %}
函数 Function
这个没什么好说的,会写程序的都知道,TWIG内置了一些函数,参考我的博客
举个例子 返回一个0到3的数组,就使用 range函数
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
流程控制
支持for循环 和 if/elseif/else结构。直接看例子吧,没什么好说的。
Members
- {{ user.username|e }}
{% for user in users %}
{% endfor %}
Members
- {{ user.username|e }}
{% for user in users %}
{% endfor %}
{% if users|length > 0 %}
- {{ user.username|e }}
{% for user in users %}
{% endfor %}
{% endif %}
{% if users|length > 0 %}
- {{ user.username|e }}
{% for user in users %}
{% endfor %}
{% endif %}
注释
{# ... #} 包围的内容会被注释掉,可以是单行 也可以是多行。
载入其他模板
详见include标签(我博客内已经翻译好哦),会返回经过渲染的内容到当前的模板里
{% include 'sidebar.html' %}
{% include 'sidebar.html' %}当前模板的变量也会传递到 被include的模板里,在那里面可以直接访问你这个模板的变量。
比如
{% for box in boxes %}
{% include "render_box.html" %}
{% endfor %}
{% for box in boxes %}
{% include "render_box.html" %}
{% endfor %}在 render_box.html 是可以访问 box变量的
加入其他参数可以使被载入的模板只访问部分变量,或者完全访问不到。参考手册
模板继承
TWIG中最有用到功能就是模板继承,他允许你建立一个“骨骼模板”,然后你用不同到block来覆盖父模板中任意到部分。而且使用起来非常到简单。
我们先定义一个基本骨骼页base.html 他包含许多block块,这些都可以被子模板覆盖。
{% block head %}
{% endblock %}
{% block head %}
{% endblock %}
我们定义了4个block块,分别是 block head, block title, block content, block footer
注意
1、block是可以嵌套的。
2、block可以设置默认值(中间包围的内容),如果子模板里没有覆盖,那就直接显示默认值。比如block footer ,大部分页面你不需要修改(省力),但你需要到时候仍可以方便到修改(灵活)
下面我看下 子模板应该怎么定义。
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
{% endblock %}
{% block content %}
Index
Welcome on my awesome homepage.
{% endblock %}
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
{% endblock %}
{% block content %}
Index
Welcome on my awesome homepage.
{% endblock %}注意 {% extends "base.html" %} 必须是第一个标签。其中 block footer就没有定义,所以显示父模板中设置的默认值
如果你需要增加一个block的内容,而不是全覆盖,你可以使用 parent函数
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
extends标签只能有一个,所以你只能有一个父模板,但有种变通到方法来达到重用多个模板到目的,具体参见手册的use标签
HTML转义
主要是帮助转义 尖括号等 , &, " 可以有两种办法。一种是用标签,另一种是使用过滤器。其实TWIG内部就是调用 php 的htmlspecialchars 函数
{{ user.username|e }}
{{ user.username|e('js') }}
{% autoescape true %}
Everything will be automatically escaped in this block
{% endautoescape %}
{{ user.username|e }}
{{ user.username|e('js') }}
{% autoescape true %}
Everything will be automatically escaped in this block
{% endautoescape %}
因为{{是TWIG的操作符,如果你需要输出两个花括号,最简单到办法就是
{{ '{{' }}
{{ '{{' }}
还可以使用 raw 标签和raw 过滤器,详细参考手册
{% raw %}
- {{ item }}
{% for item in seq %}
{% endfor %}
{% endraw %}
{% raw %}
- {{ item }}
{% for item in seq %}
{% endfor %}
{% endraw %}
macros宏
宏有点类似于函数,常用于输出一些html标签。
这里有个简单示例,定义了一个输出input标签的宏。
{% macro input(name, value, type, size) %}
{% endmacro %}
{% macro input(name, value, type, size) %}
{% endmacro %}宏参数是没有默认值的,但你可以通过default过滤器来实现。
一般来说宏会定义在其他到页面,然后通过import标签来导入,
{% import "forms.html" as forms %}
{{ forms.input('username') }}
{% import "forms.html" as forms %}
{{ forms.input('username') }}
你也可以只导入一个文件中部分宏,你还可以再重命名。{% from 'forms.html' import input as input_field, textarea %}
- Username
- {{ input_field('username') }}
- Password
- {{ input_field('password', type='password') }}
{{ textarea('comment') }}
{% from 'forms.html' import input as input_field, textarea %}
- Username
- {{ input_field('username') }}
- Password
- {{ input_field('password', type='password') }}
{{ textarea('comment') }}
上面的代码表示 从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
你可以嵌套定义
{% set foo = [1, {"foo": "bar"}] %}
{% set foo = [1, {"foo": "bar"}] %}运算符
包括数字运算+ - * / %(求余数) //(整除) **(乘方)
{{ 2 * 3 }}=6
{{ 2 * 3 }}=8
{{ 2 * 3 }}=6
{{ 2 * 3 }}=8逻辑运算 and or not
比较运算 > =
包含运算 in 以下的代码会返回 true
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}测试运算 is 这个不用多说 直接看代码
{{ 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)) %}
{{ 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函数的缩写,具体参看手册
{% for i in 0..3 %} <br> {{ i }}, <br> {% endfor %} <br> <pre name="code" class="html">{% for i in 0..3 %}<br> {{ i }},<br> {% endfor %} <p>| 使用一个过滤器<br> <br> {# output will be HELLO #} <br> {{ "hello"|upper }} <br> {# output will be HELLO #}<br> {{ "hello"|upper }}~ 强制字符串连接<br> {{ "Hello " ~ name ~ "!" }} <br> {{ "Hello " ~ name ~ "!" }}?: 三元操作符<br> {{ foo ? 'yes' : 'no' }} <br> {{ foo ? 'yes' : 'no' }}. [] 得到一个对象的属性,比如以下是相等的。<br> <br> {{ foo.bar }} <br> {{ foo['bar'] }} <br> {{ foo.bar }}<br> {{ foo['bar'] }}<br> 你还可以在一个字符串内部插入一个表达式,通常这个表达式是变量。 格式是 #{表达式}<br> {{ "foo #{bar} baz" }} <br> {{ "foo #{1 + 2} baz" }} <br> {{ "foo #{bar} baz" }}<br> {{ "foo #{1 + 2} baz" }}</p> <p><br> 空白控制<br> 和 php一样,在TWIG模板标签之后的第一个换行符会被自动删掉,其余的空白(包括 空格 tab 换行等)都会被原样输出。<br> 使用spaceless标签就可以删除这些HTML标签之间的空白<br> <br> {% spaceless %} <br> </p><div> <br> <strong>foo</strong> <br> </div> <br> {% endspaceless %} <br> <br> {# output will be <div><strong>foo</strong></div> #} <br> {% spaceless %}<br> <div> <br> <strong>foo</strong><br> </div><br> {% endspaceless %} <p>{# output will be </p><div><strong>foo</strong></div> #}<br> 使用-操作符,可以很方便的删除TWIG标签之前或之后与html标签之间的空白。<br> {% set value = 'no spaces' %} <br> {#- No leading/trailing whitespace -#} <br> {%- if true -%} <br> {{- value -}} <br> {%- endif -%} <br> <br> {# output 'no spaces' #} <br> {% set value = 'no spaces' %}<br> {#- No leading/trailing whitespace -#}<br> {%- if true -%}<br> {{- value -}}<br> {%- endif -%} <p>{# output 'no spaces' #}<br> {% set value = 'no spaces' %} <br> </p>
{# outputs '
{% set value = 'no spaces' %}
{# outputs '
结束,如果你坚持看到这里,恭喜自己吧,你又多掌握了一些知识,恭喜恭喜
摘自 jiaochangyun的专栏

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.

Retrieval-augmented generation (RAG) is a technique that uses retrieval to boost language models. Specifically, before a language model generates an answer, it retrieves relevant information from an extensive document database and then uses this information to guide the generation process. This technology can greatly improve the accuracy and relevance of content, effectively alleviate the problem of hallucinations, increase the speed of knowledge update, and enhance the traceability of content generation. RAG is undoubtedly one of the most exciting areas of artificial intelligence research. For more details about RAG, please refer to the column article on this site "What are the new developments in RAG, which specializes in making up for the shortcomings of large models?" This review explains it clearly." But RAG is not perfect, and users often encounter some "pain points" when using it. Recently, NVIDIA’s advanced generative AI solution
