简单而强大的swig.js

来源:互联网 发布:淘宝手机端分类链接 编辑:程序博客网 时间:2024/05/10 02:49

swig的简单介绍

swig是JS模板引擎,它有如下特点:

  • 根据路劲渲染页面
  • 面向对象的模板继承,页面复用
  • 动态页面
  • 快速上手
  • 功能强大

swig的变量

{{ foo.bar }}{{ foo['bar'] }}//如果变量未定义,输出空字符。

swig的标签

extends
使当前模板继承父模板,必须在文件最前 参数: file
父模板相对模板 root 的相对路径,将在后面介绍如何实现模板继承。
block
定义一个块,使之可以被继承的模板重写,或者重写父模板的同名块 参数: name
块的名字,必须以字母数字下划线开头
parent
将父模板中同名块注入当前块中
include
包含一个模板到当前位置,这个模板将使用当前上下文 参数: file
包含模板相对模板 root 的相对路径

 {% include "a.html" %} {% include "template.js" %}  //将引入的文件内容放到被引用的地方

raw
停止解析标记中任何内容,所有内容都将输出 参数: file
父模板相对模板 root 的相对路径
for
遍历对象和数组 参数:x 当前循环迭代名
in: 语法标记 y: 可迭代对象。

{% for x in y %}    <p> {{ x }}</p>{% endfor %}

if
条件语句,参数:
接受任何有效的 JavaScript条件语句

{% if foo %}    <p> foo is true </p>{% else if "foo" in bar %}    <p> foo in bar</p>{% else %}    <p> fail </p>{% endif %}

autoescape
改变当前变量的自动转义行为 参数: on
当前内容是否转义 type: 转义类型,js 或者 html,默认 html

input  = '<p>Hello "you" & \'them\'</p>';{% autoescape false %}    {{ input }}{% endautoescape %}// <p>Hello "you" & 'them'</p>{% autoescape true %}    {{ input }}{% endautoescape %}//&lt;p&gt;Hello &quot;you&quot; &amp; &#39;them&#39; &lt;/p&gt;{% autoescape true "js" %}    {{ input }}{% endautoescape %}// \u003Cp\u003EHello \u0022you\u0022 & \u0027them\u0027\u003C\u005Cp\u003E

set
设置一个变量,在当前上下文中复用

{% set foo = [0, 1, 2, 3, 4, 5] %}{% for num in foo %}   <li>{{ num }}</li>{% endfor %}

模板继承
Swig 使用 extends 和 block 来实现模板继承
example:
//layout.html

<!doctype html><html><head>    <meta charset="utf-8">    <title>{% block title %}My Site{% endblock %}</title>    {% block head %}    {% endblock %}</head><body>    {% block content %}{% endblock %}</body></html>

//index.html

{% extends './layout.html' %}{% block title %}My Page{% endblock %}{% block head %}{% parent %}{% endblock %}{% block content %}    <p>This is just an awesome page.</p>    <h1>hello,lego.</h1>    <script>        //require('pages/index/main');    </script>{% endblock %}

swig模板经过编译后:

<!doctype html><html><head>    <meta charset="utf-8">    <title>My Page</title><body>    <p>This is just an awesome page.</p>    <h1>hello,lego.</h1>    <p>test</p>    <script>        //require('pages/index/main');    </script></body></html>

swig的前景

swig使用广泛,在很多框架中使用,例如node框架yog2中,相对于其他js模板引擎,有它的好处:
1、与jade相比,更简单,jade是一个处女座的人才可以完全适应去写的,跟Python有的一拼;而且jade是一种面向对象的模板引擎,看起来并不是那么像是html了,但是关于性能的问题,尚未深入研究过。
2、与ejs相比,ejs写起来比较麻烦,格式傻傻分不清楚,满眼的符号,尤其是他的{},和jsp有的一拼:

  <% datas.forEach(function(item) { %>       <li>姓名:<%= item.name %>  年龄:<%= item.age %>  公司:<%= item.comp %></li>  <% }); %>

在性能方面,又一遍关于ejs和swig性能比较的文章,可以看出swig性能还是不错的。

0 0
原创粉丝点击