artTemplate学习笔记

最简单模板

html标签:

{{title}}

  • {{each list as value i}}
  • 索引 {{i + 1}} :{{value}}
  • {{/each}}

JS代码:

var data = {
title: ‘标签’,
list: [‘文艺’, ‘博客’, ‘摄影’, ‘电影’, ‘民谣’, ‘旅行’, ‘吉他’]
};
var html = template(‘test’, data);
document.getElementById(‘content’).innerHTML = html;

模板语法

简洁语法

推荐使用,语法简单实用,利于读写。

引用简洁语法的引擎版本,例如:

示例: {{if admin}} {{include ‘admin_content’}} {{each list}}
{{ index}}. {{value.user}}
{{/each}} {{/if}} #### 表达式 {{ 与 }} 符号包裹起来的语句则为模板的逻辑表达式。 #### 输出表达式 对内容编码输出: {{content}} 不编码输出: {{#content}} 编码可以防止数据中含有 HTML 字符串,避免引起 XSS 攻击。 #### 条件表达式 {{if admin}}

admin

{{else if code > 0}}

master

{{else}}

error!

{{/if}} #### 遍历表达式 无论数组或者对象都可以用 each 进行遍历。 {{each list as value index}}
  • {{index}} - {{value.user}}
  • {{/each}} 亦可以被简写: {{each list}}
  • {{index}} - {{value.user}}
  • {{/each}} #### 模板包含表达式 用于嵌入子模板。 {{include ‘template_name’}} 子模板默认共享当前数据,亦可以指定数据: {{include ‘template_name’ news_list}} 示例:

    {{title}}

    {{include 'list'}}
    • {{each list as value i}}
    • 索引 {{i + 1}} :{{value}}
    • {{/each}}
    var data = { title: '嵌入子模板', list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'] }; var html = template('test', data); document.getElementById('content').innerHTML = html;
    辅助方法

    使用template.helper(name, callback)注册公用辅助方法:

    template.helper(‘dateFormat’, function (date, format) {
    // ..
    return value;
    });
    模板中使用的方式:

    {{time | dateFormat:’yyyy-MM-dd hh:mm:ss’}}
    支持传入参数与嵌套使用:

    {{time | say:’cd’ | ubb | link}}

    在javascript中存放模板

    var source = ‘


    • + ‘{{each list as value i}}’
      + ‘
    • 索引 {{i + 1}} :{{value}}

    • + ‘{{/each}}’
      + ‘
    ‘;

    var render = template.compile(source);
    var html = render({
    list: [‘摄影’, ‘电影’, ‘民谣’, ‘旅行’, ‘吉他’]
    });

    document.getElementById(‘content’).innerHTML = html;

    print方法

    print

    {{print a b c}} var html = ''; var data = { a: 'hello', b: '--world', c: '--!!!' }; html = template('test', data); document.write(html);

    原生语法

    template方法

    template(id, data)

    根据 id 渲染模板。内部会根据document.getElementById(id)查找模板。

    如果没有 data 参数,那么将返回一渲染函数。

    template.compile(source, options)

    将返回一个渲染函数。演示

    template.render(source, options)

    将返回渲染结果。

    template.helper(name, callback)

    添加辅助方法。

    例如时间格式器:演示

    template.config(name, value)

    更改引擎的默认配置。

    字段 类型 默认值 说明
    openTag String ‘{{’ 逻辑语法开始标签
    closeTag String “}}” 逻辑语法结束标签
    escape Boolean true 是否编码输出 HTML 字符
    cache Boolean true 是否开启缓存(依赖 options 的 filename 字段)
    compress Boolean false 是否压缩 HTML 多余空白字符

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值