标签:swig-js swigjs nodejs node-js js模板引擎
A simple, powerful, and extendable JavaScript Template Engine。
简单概括:JS模板引擎。
参见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中通过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
}
Super Quick Start:
Swig.js docs
标签:swig-js swigjs nodejs node-js js模板引擎
原文地址:http://blog.csdn.net/hai8902882/article/details/46419113