Installation

Via NPM:

$ npm install swig --save

Basic Usage

Swig has multiple ways to compile and render templates. Check the API documentation for more detailed information and usage.

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!' }})); // Immediately render a Swig template from a string
console.log(swig.render('{% if foo %}Hooray!{% endif %}', { locals: { foo: true }}));

Variables

Variables that are passed to templates can be output using double-curly-brackets: . All variable output is automatically autoescaped, with the exception of function output.

Notation

Accessing properties of objects can be done using either dot-notation or bracket-notation. The following examples are equivalent:

{{ foo.bar }}
// is equivalent to
{{ foo['bar'] }}

However, notation style follows the same rules as JavaScript. If a key includes non-alpha-numeric characters, it must be accessed using bracket-notation, not dot-notation.

Bad!

{{ foo.chicken-tacos }}

The above would be the same as attempting to subract tacos from foo.chicken{{ foo.chicken - tacos }}

Good!

{{ foo['chicken-tacos'] }}

Undefined vs Falsy Values

If a variable is not defined, don't worry, your template won't explode. Instead, an empty-string will be output in its place. However, falsy values like null, false, 0 will be rendered as they are.

Filters

Variables can be modified using using special, chainable control structures called Filters:

{{ name|title }} was born on {{ birthday|date('F jS, Y') }}
// =>Jane was born on July 6th, 1985

Functions

Variables can also be JavaScript functions. It is important to note that, regardless of your autoescape setting, functions will not be auto-escaped.

var locals = { mystuff: function mystuff() { return '<p>Things!</p>'; } };
swig.render('{{ mystuff() }}', { locals: locals });
// => <p>Things!</p>

If you want to enforce escaping output on functions, just pipe them to the escape filter.

{{ mystuff()|escape }}
// => &lt;p&gt;Things&lt;/p&gt;

Logic Tags

Swig includes some basic operational blocks, called Tags, for helping you control output on a larger scale than variables. Tags are written using curly-percent syntax: .

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

end tags may also have any set of extra context within them, and will just be ignore. This is useful for scoping and understanding which block you are closing and where.

{% block tacos %}
//...
{% endblock tacos %}
{% block burritos %}
{% if foo %}
// ...
{% endif the above will render if foo == true %}
{% endblock burritos %}

View the Tags documentation for a full list of tags and usage instructions.

Comments

Comment tags are simply ignored by the parser. They will removed before your templates are rendered so that no one can see them unless they have access to your source code. Comments are written using the curly-hash syntax:

{#
This is a comment.
It will be fully stripped and ignored during parsing.
#}

Whitespace Control

Any whitespace in your templates is left in your final output templates. However, you can control the whitespace around logic tags by using whitespace controls.

To remove whitespace, simply put a dash (-) at the beginning or end of your tag to remove the preceding or following whitespace, respectively.

// seq = [1, 2, 3, 4, 5]
{% for item in seq -%}{{ item }}
{%- endfor %}

// =>12345

Note: there must not be any space between the tag open/close mark and the dash.

Template Inheritance

Swig uses extends & block for template inheritance.

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

Using Swig with Express.js

Swig is easily compatible with Express, the simple web application framework for node. The following is a basic example of integrating Swig with Express:

var app = require('express')(),
swig = require('swig'),
people; // This is where all the magic happens!
app.engine('html', swig.renderFile); app.set('view engine', 'html');
app.set('views', __dirname + '/views'); // Swig will cache templates for you, but you can disable
// that and use Express's caching instead, if you like:
app.set('view cache', false);
// To disable Swig's cache, do the following:
swig.setDefaults({ cache: false });
// NOTE: You should always cache templates in a production environment.
// Don't leave both of these to `false` in production! app.get('/', function (req, res) {
res.render('index', { /* template locals context */ });
}); app.listen(1337);
console.log('Application Started on http://localhost:1337/');

【转】Swig Getting Started的更多相关文章

  1. Node.js-视图引擎【1】-Swig集成express的安装与配置

    node.js视图引擎,选来选去发现Swig最符合我的胃口哈哈. 一.安装Swig视图引擎 npm install -g swig 二.在node.js代码中配置如下 var app = requir ...

  2. express+gulp构建项目(五)swig模板

    这里的文件负责配置swig模板引擎. index.js var jsonHash = require('./json_file'); var staticTag = require("./t ...

  3. Python、Ruby中的SWIG使用案例

    案例一:Python通过SWIG使用C码 linux系统 照着文档[1]做就是了~! 案例二:Python程序调用张华平博士最新发布的中文分词库“NLPIR – ICTCLAS2013”为例~! wi ...

  4. 安装m2crypto报错swig error : Unrecognized option -builtin

    M2Crypto 是最完整的为 Python 包装 OpenSSL 的 RSA,DSA,DH,EC,HMACs,消息摘要,对称密码算法(包括AES)的一个库工具.而自从 M2Crypto 升级到版本 ...

  5. swig之于c++

    [namespace] namespace nsTest1 { int nsAdd(int a, int b) { return a + b; } } namespace nsTest2 { int ...

  6. crossplatform---Nodejs in Visual Studio Code 05.Swig+Bootstrap

    1. 开始 准备好Express+Swig的练习代码:https://github.com/Mengkzhaoyun/nodepractise 准备好AdminLTE后台管理模版:https://ww ...

  7. Swig 使用指南

    如何使用 API swig.init({ allowErrors: false, autoescape: true, cache: true, encoding: 'utf8', filters: { ...

  8. Demo Swig

    演示使用swig工具创建c语言的java接口,生成.so库和java接口文件. 在此之前先要安装swig,安装方法:sudo apt-get install swig 1.使用eclipse创建工程. ...

  9. html 模板 swig 预编译插件 grunt-swig-precompile

    GitHub grunt-swig-precompile NPM grunt-swig-precompile 在书写前端静态页面的时候,每个页面总在书写很多重复的标签. 为了提高效率,结合 swig. ...

  10. 在Python中调用C++,使用SWIG

    http://www.coder4.com/archives/2141 SWIG:Simplified Wrapper and Interface Generator,顾名思义,就是将C/C++包装为 ...

随机推荐

  1. 利用 AWK 的数值计算功能提升工作效率(转载)

    Awk 是一种优秀的文本样式扫描和处理工具.转文侧重介绍了 awk 在数值计算方面的运用,并通过几个实际工作中的例子,阐述了如何利用 awk 的计算功能来提高我们的工作效率.转文源自IBM Bluem ...

  2. REVERSE!REVERSE!REVERSE!

    形式汇总: 206. Reverse Linked List 92. Reverse Linked List II:Given a string and an integer k, you need ...

  3. 复杂度分析 quick sort&merge sort

    空间复杂度看新开了什么数据结构就够了 公式=几个点*每个点执行了多少次 二叉树都是n次 二分法查找:lgn 全部查找:n n:找一个数,但是两边都要找.相当于遍历.类似于rotated sorted ...

  4. iframe父窗口和子窗口之间的调用

    1>父窗口获取子窗口 js方法 document.getElementById('if1').contentWindow.document: window.frames["if1&qu ...

  5. springmvc使用数组接收页面商品列表批量删除传过来的参数,并完成批量删除的操作。

    1.1 需求 在商品列表页面选中多个商品,然后删除. 1.2 需求分析 此功能要求商品列表页面中的每个商品前有一个checkbox,选中多个商品后点击删除按钮把商品id传给controller,根据商 ...

  6. 安全运维 -- Linux服务器使用公私钥密匙证书登录

    环境:Ubuntu 16 前言 黑客遍地都是,ssh/pop3/ftp等爆破工具的流行让站长的日常运维工作量大大加重.Metasplot,Bruter等工具更是针对以上协议有专门 的破解方法,有字典破 ...

  7. .net core webapi 部署windows server 2008 r2 笔记

    WebAPI部署文档 安装dotnet-dev-win-x64.1.0.4 安装DotNetCore.1.1.0-WindowsHosting 安装vc_redist.x64 安装Windows6.1 ...

  8. Linux wget命令

    一.简介 wget是一个Linux系统中的下载文件的工具,它用在命令行下.对于Linux用户是必不可少的工具,我们经常要下载一些软件或从远程服务器恢复备份到本地服务器.wget支持HTTP,HTTPS ...

  9. POJ 3709 K-Anonymous Sequence - 斜率优化dp

    描述 给定一个数列 $a$, 分成若干段,每段至少有$k$个数, 将每段中的数减少至所有数都相同, 求最小的变化量 题解 易得到状态转移方程 $F_i = \min(F_j  + sum_i - su ...

  10. POJ 1300.Door Man 欧拉通路

    Door Man Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 2596   Accepted: 1046 Descript ...