JavaScript模板引擎原理与用法详解

2019-09-13 15:27 来源:易采站长站 作者:于丽 点击: 评论:

A-A+

原标题:JavaScript模板引擎原理与用法详解

本文实例讲述了JavaScript模板引擎原理与用法。,具体如下:

一、前言

什么是模板引擎,说的简单点,就是一个字符串中有几个变量待定。比如:

var tpl = 'Hei, my name is <%name%>, and I\'m <%age%> years old.';

通过模板引擎函数把数据塞进去,

var data = {
  "name": "Barret Lee",
  "age": "20"
};
var result = tplEngine(tpl, data);
//Hei, my name is Barret Lee, and I'm 20 years old.

那这玩意儿有什么作用呢?其实他就是一个预处理器(preprocessor),搞php开发的童鞋对Smarty必然是十分熟悉,Smarty是一个php模板引擎,tpl中待处理的字符通过数据匹配然后输出相应的html代码,加之比较给力的缓存技术,其速度和易用性是非常给力的!JS Template也是一样的,我们的数据库里保存着数以千万计的数据,而每一条数据都是通过同一种方式输入,就拿上面的例子来说,我们不可能在数据库里存几千条"Hei, my name...",而是只保存对应的name和age,通过模板输出结果。

JS模板引擎应该做哪些事情?看看下面一串代码:

var tpl = '<% for(var i = 0; i < this.posts.length; i++) {' + 
  'var post = posts[i]; %>' +
  '<% if(!post.expert){ %>' +
    '<span>post is null</span>' +
  '<% } else { %>' +
    '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><% post.expert %> at <% post.time %></a>' +
  '<% } %>' +
'<% } %>';

一个基本的模板引擎至少可以保证上面的代码可以正常解析。如送入的数据是:

var data = {
  "posts": [{
    "expert": "content 1",
    "time": "yesterday"
  },{
    "expert": "content 2",
    "time": "today"
  },{
    "expert": "content 3",
    "time": "tomorrow"
  },{
    "expert": "",
    "time": "eee"
  }]
};

可以输出:

<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 1 at yesterday</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 2 at today</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 3 at tomorrow</a>
<span>post is null</span>

【易采站长站编辑:秋军】