art-template模板、语法,以及express-art-template模板引擎

一、什么是art-template

art-template 是一个简约、超快的模板引擎。
它采用作用域预声明的技术来优化模板渲染速度,从而获得接近 JavaScript 极限的运行性能,并且同时支持 NodeJS 和浏览器。

art-template 的特性:
1.拥有接近 JavaScript 渲染极限的的性能
2.调试友好:语法、运行时错误日志精确到模板所在行;支持在模板文件上打3.断点(Webpack Loader)
4.支持 Express、Koa、Webpack
5.支持模板继承与子模板
6.浏览器版本仅 6KB 大小

二、模板

art-template 同时支持两种模板语法。标准语法可以让模板更容易读写;原始语法具有强大的逻辑处理能力。

标准语法:

{{if user}}
  <h2>{{user.name}}</h2>
{{/if}}

原始语法:

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

渲染模板:

var template = require('art-template');
var html = template(__dirname + '/tpl-user.art', {
    user: {
        name: 'aui'
    }
});

三、语法

1、输出:
标准语法:

{{value}}
{{data.key}}
{{data['key']}}
{{a ? b : c}}
{{a || b}}
{{a + b}}

原始语法:

<%= value %>
<%= data.key %>
<%= data['key'] %>
<%= a ? b : c %>
<%= a || b %>
<%= a + b %>

2、条件
标准语法:

{{if value}} ... {{/if}}
{{if v1}} ... {{else if v2}} ... {{/if}}

原始语法:

<% if (value) { %> ... <% } %>
<% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>

条件:

// 基于nodejs来渲染art-template
const http = require('http');
// 引入art-template模板
var template = require('art-template');
http.createServer(function(req, res) {
    // 解决中文乱码的问题
    res.writeHead(200, {
            "Content-type": "text/html;charset=utf-8"
        })
        // 根据req.url来判断请求的路径
    if (req.url === '/demo.html') {
        console.log("解析demo.art模板,并发送给用户");
        var html = template(__dirname + '/demo.art', {
            // user: {
            //     name: 'aui'
            // }
            title: "标题",
            user: {
                name: "小张"
            },
            list: ["笑", "嘿", "哈"]
        });
        res.end(html);
        } else {
        res.writeHead(404, {
            "Content-type": "text/html;charset=utf-8"
        })
        res.end('没有您要访问的页面');
    }
}).listen(3000);
        

demo.art:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="content"></div>
    {{if user}}
    <h2>{{user.name}}</h2>
    {{/if}}

    <% if (user) { %>
        <h2>
            <%= user.name %>
        </h2>
        <% } %>

            <h1>{{title}}</h1>
            <ul>
                {{each list as value i}}
                <li>索引 {{i + 1}} :{{value}}</li>
                {{/each}}
            </ul>

</body>

</html>

最终页面显示:
在这里插入图片描述
3.循环
标准语法:

{{each target}}
    {{$index}} {{$value}}
{{/each}}

原始语法:

<% for(var i = 0; i < target.length; i++){ %>
    <%= i %> <%= target[i] %>
<% } %>

循环:

// 基于nodejs来渲染art-template
const http = require('http');
// 引入art-template模板
var template = require('art-template');
http.createServer(function(req, res) {
    // 解决中文乱码的问题
    res.writeHead(200, {
            "Content-type": "text/html;charset=utf-8"
        })
        // 根据req.url来判断请求的路径
  if (req.url === '/grammar.do') {
        var html = template(__dirname + '/grammar.art', {
            // 数组类型
            users: [{
                    id: 1001,
                    username: "小刘",
                    userpwd: "123"
                },
                {
                    id: 1002,
                    username: "小张",
                    userpwd: "456"
                },
                {
                    id: 1003,
                    username: "小陈",
                    userpwd: "789"
                },
            ]
        });
        res.end(html);
         } else {
        res.writeHead(404, {
            "Content-type": "text/html;charset=utf-8"
        })
        res.end('没有您要访问的页面');
    }
}).listen(3000);

在grammar.art中,循环用户信息:

 <h2>所有用户数据</h2>
    <ul>{{each users}}
        <li>{{$index}} :{{$value.id}}-{{$value.username}}-{{$value.userpwd}}</li> {{/each}}</ul><br>
    <!--  each 数组的  as别名  -->
    <!-- 第一个别名对应的是原本的$value  第二个别名对应的是原本的$index -->
    <ul>{{each users as user i}}
        <li>{{i}}:{{user.id}}-{{user.username}}-{{user.userpwd}}</li>
        {{/each}}
    </ul>

页面显示:
在这里插入图片描述
4.模板继承
标准语法:

{{extend './parent.art'}}
{{block 'head'}} ... {{/block}}

原始语法:

<% extend('./parent.art') %>
<% block('head', function(){ %> ... <% }) %>

app.js:

if (req.url === '/child.do') {
        var html = template(__dirname + '/child.art', {
            title: "子页面标题",
            heading: "我是标题标签的内容"
        })
        res.end(html);
     }

parent.art:

<!--parent.art-->
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{block 'title'}}My Site{{/block}}</title>

    {{block 'head'}}
    <link rel="stylesheet" href="./css/custom.css"> {{/block}}
</head>

<body>
    {{include './header.art'}} {{block 'content'}}{{/block}} {{include './footer.art'}}
</body>

</html>

child.art:

<!-- 让child.art继承父模板 -->
{{extend './parent.art'}} {{block 'title'}}{{title}}{{/block}} {{block 'head'}}
<link rel="stylesheet" href="./css/custom.css"> {{/block}} {{block 'content'}} {{$data}}
<p>This is just an awesome page.</p>
<h1>我是body里面的h1 {{heading}}</h1>


<% $imports.log('hello world') %>
    {{/block}}

5.过滤器

过滤器:

template.defaults.imports.dateFormat = function(date, format){/*[code..]*/};
template.defaults.imports.timestamp = function(value){return value * 1000};

标准语法:

{{date | timestamp | dateFormat 'yyyy-MM-dd hh:mm:ss'}}

{{value | filter}} 过滤器语法类似管道操作符,它的上一个输出作为下一个输入。

原始语法:

<%= $imports.dateFormat($imports.timestamp(date), 'yyyy-MM-dd hh:mm:ss') %

在这里插入图片描述
child.art中:
在这里插入图片描述

四、express-art-template模板引擎

express-art-template模板引擎可以让art-template模板引擎更好的和Express框架配合。

express的engine()方法:
当渲染后缀为art的模板时使用express-art-template
第一个参数是模板的后缀
第二个参数是使用的什么模板

express的set()方法:
1.设置模板存放目录
第一个参数是设置存放模板目录的文件夹
第二个参数是存放模板的绝对路径

2.设置默认的模板后缀,设置模板时,如果没有写模板后缀就使用当前设置的模板后缀
第一个参数是 默认模板的配置项
第二个参数是后缀的名字

express的render()方法:渲染模板(在该方法的内部会自动拼接后缀、模板与数据的拼接、把结果相应给客户端)
参数是模板名称。
对象,即向模板中传递的数据

app.js:

// 引入express框架,依赖express框架搭建服务器
var express = require('express');
// 创建web服务器
var app = express();
// 引入path模块
const path = require('path');

// 渲染引擎设置
app.engine('art', require('express-art-template'));
// 开启debug
app.set('view options', {
    debug: process.env.NODE_ENV !== 'production'
});
// 设置视图,表示要解析的模板文件在哪儿
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'art');

// routes
app.get('/', function(req, res) {
    // res.render()渲染模板引擎
    res.render('index.art', {
        count: 31,
        userList: [{
                id: 1001,
                userName: '小刘',
                userPwd: '123',
                sex: 1
            },
            {
                id: 1002,
                userName: '小张',
                userPwd: '456',
                sex: 1
            },
            {
                id: 1003,
                userName: '小陈',
                userPwd: '789',
                sex: 0
            }
        ],
        pageNum: 1,
        pageSize: 3,
        pageCount: 11
    });
});

app.listen(3000, () => {
    console.log('example app listening on port 3000');
})

index.art:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>所有用户的信息</h1>
    <table>
        <thead>
            <tr>
                <td>用户编号</td>
                <td>用户名</td>
                <td>密码</td>
                <td>性别</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>
            {{each userList as user}}
            <tr>
                <td>{{user.id}}</td>
                <td>{{user.userName}}</td>
                <td>{{user.userPwd}}</td>
                <!-- <td>{{user.sex}}</td> -->
                <td>
                    {{if user.sex=='1'}}  {{else if user.sex=='0'}}  {{/if}}
                </td>
                <td>
                    <a href="http://localhost:3000/user/delete/{{user.id}}">删除</a>
                    <a href="http://127.0.0.1:3000/user/update/{{user.id}}">修改</a>
                </td>
            </tr>
            {{/each}}
            <tr>
                <td colspan="5">
                    <!-- 总条目数:{{count}}|总页数:{{pageCount}}|当前页:{{pageNum}} -->
                    共{{count}}页
                    <a href="http://localhost:3000/user/query/{{pageNum-1}}/{{pageSize}}">上一页</a>
                    <a href="http://localhost:3000/user/query/{{pageNum+1}}/{{pageSize}}">下一页</a> 当前页/总页数:{{pageNum}}/{{pageCount}}
                </td>
            </tr>
        </tbody>
    </table>
</body>

</html>

页面显示:
在这里插入图片描述
页面检查显示:
在这里插入图片描述

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值