当前位置: 首页 > 工具软件 > art-template > 使用案例 >

art-template

洪知
2023-12-01

art-template

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}}
  1. target 支持 arrayobject 的迭代,其默认值为 $data
  2. $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')}}
 类似资料: