https://aui.github.io/art-template/zh-cn/docs
如果渲染模板的时候,传递过来的数据集中又user数据
那么在页面中显示h2标签,h2标签里面用户的名字
<script id="demo01" type="text/html">
{{if user}}
<h2>{{user.name}}</h2>
{{/if}}
</script>
<script>
<% if (user) { %>
<h2><%= user.name %></h2>
<% } %>
</script>
渲染页面(demo.art)
如果是art文件, 我们可以通过NodeJS引入模板,调用Art-template API 来实现 ,直接放入指定的标签
const template = require('art-template')
//template(filename, content) 根据模板名渲染模板,
const html = template(__dirname + '/tpl-user.art', {
user: {
name: 'aui'
}
})
如果是html页面的script标签使用了art 模板 (demo.html)
我们可以在浏览器中实时编译
1. 引入文件
2. 调用template()方法
<script src="template-web.js"></script>
<script id="demo01" type="text/html">
{{if user}}
<h2>{{user.name}}</h2>
{{/if}}
</script>
<script>
// template(模板id, data) 根据模板名渲染模板,
const html = template(demo01, {
user: {
name: 'zs'
}
})
document.getElementById('content').innerHTML = html
</script>
(grammar.art)
{{@ value }}
{{if value}} ... {{/if}} {{if v1}} ... {{else if v2}} ... {{/if}}
{{each target}} {{$index}} {{$value}} {{/each}}
target
支持 array
与 object
的迭代,其默认值为 $data
。$value
与 $index
可以自定义:{{each target val key}}
。{{set temp = admin}}
(parent.art)(child.art)(header.art)
<!--parent.art文件里-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{block 'title'}}My Site{{/block}}</title>
{{block 'head'}}
<link rel="stylesheet" href="main.css">
{{/block}}
</head>
<body>
{{block 'content'}}{{/block}}
</body>
</html>
{{extend ‘./parent.art’}} 继承骨架
将网站的公共部分(头部,底部)抽离到单独的文件中
{{include ‘./header.art’}}
定义一个可以在模板中使用的函数
template.defaults.imports.dateFormat = function(date, format){/*[code..]*/}; template.defaults.imports.timestamp = function(value){return value * 1000};
template.defaults.debug
art-template 内建调试器,能够捕获到语法与运行错误,并且支持自定义的语法。在 NodeJS 中调试模式会根据环境变量自动开启:process.env.NODE_ENV !== 'production'
设置 template.defaults.debug=true
后,等同于:
{
"cache": false,
"minimize": false,
"compileDebug": true
}
template.defaults.imports
模板通过 $imports
可以访问到模板外部的全局变量与导入的变量。
template.defaults.imports.log = console.log;
{{$imports.log('hello world')}}