Swig.js
A simple, powerful, and extendable JavaScript Template Engine。
简单概括:JS模板引擎。
Why to use
- 根据路劲渲染页面
- 面向对象的模板继承,页面更复用
- 动态页面
- 高速上手
- 功能强大
- Others
How to use
參见swig.js官网
项目实例
页面复用
大部分页面都有header 和 footer区域,能够通过继承页面实现复用,详细例如以下:
layout.html
<html>
<head>
</head>
<body>
<div class="header-container">
...
</div>
{% block content %}{% endblock %}
<div class="footer-container">
...
</div>
</body>
</html>
welcome.html
// 根据实际文件夹填写
{% extends '../layout.html' %}
{% block content %}
<div class="content-container">
<h1>hello swig.js</h1>
</div>
{% endblock %}
信息、功能函数配置化
企业信息、全部权、工商注冊号等信息,可将这些信息存在在system-params.json中,还能够加入实时计算函数。然后通过swig.js显示和调用:
system-params.json:
{
"isDevMode": "true",
"corporation": "CCCCCCCC",
"ICPNumber": "沪ICP备xxxxxxxx号",
...
}
app.js
var systemParams = require('./config/system-params.json'),
swig = require('swig');
swig.setDefaults({
cache: !systemParams.isDevMode,
locals: {
now: function () {
return new Date();
},
systemParams: systemParams
}
});
layout.html
<html>
...
<body>
{% block content %}{% endblock %}
<div class="footer-container">
<p class="text-center">
<span>Copyright © {{now() | date('Y')}}</span>
<span>{{systemParams.corporation}}</span>
<span>{{systemParams.ICPNumber}}</span>
</p>
</div>
</body>
</html>
Express.js 和 Require.js整合
在Express.js中通过swig.js路劲渲染页面,页面中使用require.js的require(deps, callback)形式载入页面须要的js:
app.js
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
routers.js
module.exports = [{
path: '/',
view: 'default/welcome',
data: {
title: 'welcome',
requireScripts: [
'controllers/default/welcome-controller'
],
styles: [
'default/welcome.css'
]
}
}];
config-routers.js
var routers = require('./routers');
...
for ... {
...
router.get(routers[i].path, function(req, res) {
res.render(routers[i].view, routers[i].data, routers[i].callback);
});
}
layout.html
<html>
<head>
...
{% if styles %}
{% for style in styles %}
<link rel="stylesheet" href="{{style}}" />
{% endfor %}
{% endif %}
...
</head>
<body>
...
<script type="text/javascript">
var GlobalConfig = {
requireScripts: []
};
// add require scripts by page config
{% if requireScripts %}
{% for script in requireScripts %}
GlobalConfig.requireScripts.push('{{ script }}');
{% endfor %}
{% endif %}
</script>
<script src="/lib/require/require.js"></script>
<!-- require.js配置信息 -->
<script src="/main.js"></script>
<!-- require(deps, callback)载入页面依赖js -->
<script src="/bootstrap.js"></script>
</body>
</html>
bootstrap.js
// add others js
GlobalConfig.requireScripts.push('...');
requirejs(GlobalConfig.requireScripts, function () {
// todo
}
Others
Super Quick Start:
Swig.js docs