当前位置:网站首页>swig 语法介绍
swig 语法介绍
2022-08-05 11:35:00 【为为为什么】
Next 主题使用swig引擎,swig 是node端的一个优秀简洁的模板引擎,本文介绍swig基本语法。
特性
- 支持大多数主流浏览器。
- 表达式兼容性好。
- 面向对象的模板继承。
- 将过滤器和转换应用到模板中的输出。
- 可根据路劲渲染页面。
- 支持页面复用。
- 支持动态页面。
- 可扩展、可定制。
安装
$ npm install swig --save基本用法
swig有多种实现方式来编译和渲染模板
var swig = require('swig');
// Compile a file and store it, rendering it later
var tpl = swig.compileFile('/path/to/template.html');
console.log(tpl({ article: { title: 'Swig is fun!' }}));
// 直接渲染字符串模板
console.log(swig.render('{% if foo %}Hooray!{% endif %}', { locals: { foo: true }}));变量
模板中的变量使用双大括号来声明。例如
{{a}}属性
变量的属性可以使用
.或者[ ]来访问,如下两个是等价的:
{{ foo.bar }}
// is equivalent to
{{ foo['bar'] }}他遵循和javascript一样的原则,如果关键词中有
-,则必须使用[]来访问属性,不能使用.
Bad!
{{ foo.chicken-tacos }}Good!
{{ foo['chicken-tacos'] }}未定义和空值
如果一个变量未定义或者是空值,在渲染的时候,将会在相应的位置输出一个空的字符串,而不会报异常。
过滤器
变量可以用特殊的链式结构进行修改过滤。
{{ name|title }} was born on {{ birthday|date('F jS, Y') }}
// => Jane was born on July 6th, 1985方法(函数)
变量也可以是 JavaScript functions. 值得注意的是,不管你的 autoescape设定是什么样的,方法都不会被 auto-escaped.
var locals = { mystuff: function mystuff() { return '<p>Things!</p>'; }};
swig.render('{{ mystuff() }}', { locals: locals });
// => <p>Things!</p>如果要对函数强制转义输出,只需通过管道将其传递到转义筛选器。
{{ mystuff()|escape }}
// => <p>Things</p>逻辑标签
Swig包含一些基本的可选的代码块,叫做标签,使用标签可以更好的控制模板的渲染输出。标签示例如下:
{% if foo %}bar{% endif %}
// Create a list of people, only if there are items in the people array
{% for person in people %}
{% if loop.first %}<ol>{% endif %}
<li>{{ person.name }}</li>
{% if loop.last %}</ol>{% endif %}
{% endfor %}其中
{ % endif % }和{ % endfor % }是结束标签,用于表明代码块的的结束。
{% block tacos %}
//...
{% endblock tacos %}
{% block burritos %}
{% if foo %}
// ...
{% endif %} //the above will render if foo == true
{% endblock burritos %}更多关于tag的信息,请查看官方文档,这里挑几个重点的经常见到的说说。
block标签
用于声明一个代码块,继承的子模板中间可以改写或者拓展父模板中同名的代码块。也可查看#继承
{% block body %}...{% endblock %}if-else-endif和if-elseif-endif标签
这个与java中的if功能类似,做条件判断时使用。满足条件的内容将会被输出。
{% if x|lower === 'tacos' %}
You can use filters on any operand in the statement.
{% endif %}{% if x in y %}
If x is a value that is present in y, this will return true.
{% endif %}{% if false %}
Tacos
{% elseif true %}
Burritos
{% else %}
Churros
{% endif %}
// => Burritosextends 标签
使当前的模板继承一个父模板,这个标签必须位于模板的最前面。其他查看#继承
{% extends "./layout.html" %}for标签
用于遍历对象和数组时使用。
参数
Name | Type | 可选 | Default | 描述 |
|---|---|---|---|---|
key | literal | undefined | A shortcut to the index of the array or current key accessor. | |
variable | literal | undefined | The current value will be assigned to this variable name temporarily. The variable will be reset upon ending the for tag. | |
in | literal | undefined | Literally, “in”. This token is required. | |
object | object | undefined | An enumerable object that will be iterated over. |
Returns
loop.index: The current iteration of the loop (1-indexed)
loop.index0: The current iteration of the loop (0-indexed)
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.key: If the iterator is an object, this will be the key of the current item, otherwise it will be the same as the loop.index.
loop.first: True if the current object is the first in the object or array.
loop.last: True if the current object is the last in the object or array.
示例
// obj = { one: 'hi', two: 'bye' };
{% for x in obj %}
{% if loop.first %}<ul>{% endif %}
<li>{{ loop.index }} - {{ loop.key }}: {{ x }}</li>
{% if loop.last %}</ul>{% endif %}
{% endfor %}
// => <ul>
// <li>1 - one: hi</li>
// <li>2 - two: bye</li>
// </ul>// arr = [1, 2, 3]
// Reverse the array, shortcut the key/index to `key`
{% for key, val in arr|reverse %}
{{ key }} -- {{ val }}
{% endfor %}
// => 0 -- 3
// 1 -- 2
// 2 -- 1import
Source: lib/tags/import.js
允许你引入定义在别的文件当中的宏到你当前的模板文件当中。
The import tag is specifically designed for importing macros into your template with a specific context scope. This is very useful for keeping your macros from overriding template context that is being injected by your server-side page generation.
参数
Name | Type | Optional | Default | Description |
|---|---|---|---|---|
file | string orvar | undefined | Relative path from the current template file to the file to import macros from. | |
as | literal | undefined | Literally, “as”. | |
varname | literal | undefined | Local-accessible object name to assign the macros to. |
示例
{% import './formmacros.html' as form %}
{{ form.input("text", "name") }}
// => <input type="text" name="name">
{% import "../shared/tags.html" as tags %}
{{ tags.stylesheet('global') }}
// => <link rel="stylesheet" href="/global.css">注释
Comments注释在渲染时将会被忽略,他们在渲染之前就会移除,所以没人能看到你的注释,除非他们查看你的源代码。
{ #
This is a comment.
It will be fully stripped and ignored during parsing.
# }空格控制符
模板中的任何空格都会被输出在最终生成的页面上。然而,你可以使用空格控制符来消除空格。
在tag的前面或者后面添加
-来移除前面或者后面的空格。
// seq = [1, 2, 3, 4, 5]
{% for item in seq -%}{{ item }}
{%- endfor %}
// => 12345注意 没有任何空格输出
继承
swig使用
extends关键字来对模板进行继承
- layout.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}My Site{% endblock %}</title>
{% block head %}
<link rel="stylesheet" href="main.css">
{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>- index.html
{% extends 'layout.html' %}
{% block title %}My Page{% endblock %}
{% block head %}
{% parent %}
<link rel="stylesheet" href="custom.css">
{% endblock %}
{% block content %}
<p>This is just an awesome page.</p>
{% endblock %}d模板
index.html继承自layout.html,并且改写或者实现了其中的内容。
参考:
https://www.jianshu.com/p/c5d333e6353chttp://node-swig.github.io/swig-templates/docs/api/#CacheOptionshttp://node-swig.github.io/swig-templates/docs/api/#CacheOptions
边栏推荐
猜你喜欢

有多一只“手”的机器狗出没?就在昇腾AI开发者创享日·南京站

Nature:猪死亡1小时后,器官再次运转

五大理由告诉你为什么开发人员选择代码质量静态分析工具Klocwork来实现软件安全

shell编程流程控制练习

灰度值与热成像理解

The training set Loss converges, but the test set Loss oscillates violently?

365 days challenge LeetCode1000 questions - Day 050 add a row to the binary tree binary tree

官方发布·2022南京智博会定于10月份在新庄国展召开

数据治理体系演进简介

623. Add a row to a binary tree: Simple binary tree traversal problems
随机推荐
学生信息管理系统(第一次.....)
低代码平台开发有什么好处?
问题征集丨ECCV 2022中国预讲会 · Panel专题研讨会
[7.29-8.5] Review of wonderful technical blog posts in the writing community
Apache APISIX Ingress v1.5-rc1 发布
力扣330 按要求补齐数组(贪心)
自定义过滤器和拦截器实现ThreadLocal线程封闭
How about Ping An Mengwa Card Insurance?Let parents read a few ways to identify products
微服务结合领域驱动设计落地
Detailed explanation of PPOCR detector configuration file parameters
How to write a blog with Golang - Milu.blog development summary
脱光衣服待着就能减肥,当真有这好事?
hdu1455 Sticks(搜索+剪枝+剪枝+.....+剪枝)
163_Tricks_Power BI one-click batch creation of custom field parameters
Exploration and practice of transaction link under multi-service mode
互联网行业凛冬之至,BATM的程序员是如何应对中年危机的?
CenOS MySQL入门及安装
Naive bayes
解决2022Visual Studio中scanf返回值被忽略问题
图像分割模型——segmentation_models_pytorch和albumentations 组合实现多类别分割