推荐五款流行的JavaScript模板引擎

推荐五款流行的JavaScript模板引擎

近日一位20岁的开发者Jack Franklin在《The top 5 JavaScript templating engines》一文中向开发者们推荐了5款流行的JavaScript模板引擎。下面为该文的译文。

当你创建JavaScript应用时,你必然会用到JavaScript模板。当对HTML进行更新时,你可使用模板来代替库(如jQuery),使用模板可以大大简化你的代码。该文将例举当前较流行的一些模板库。

1.Mustache

Mustache通常被称为JavaScript模板的基础。另一个流行的解决方案Hanldebars实际上就是基于Mustache构建而成的。这并不意味着Mustache是一个不好的模板解决方案。下面例举一例:

1

2

Mustache.render("Hello,  {{name}}", { name: "Jack" });

// 返回: Hello, Jack

一旦在页面中包含了Mustache,你就可以访问全局对象“Mustache”。你可使用其中最主要的方法“render”,它包含两个参数。首个参数是实际的模板,第二个参数则为需要传入的参数值。

上例中,你可以看见“{{name}}”。其中的“{{}}”实际上为Mustache的语法,表示一个占位符。当Mustache对其进行编译时,它将在传入的对像中寻找“name”属性,并用该属性的值(该例中为“Jack”)来代替“{{name}}”

在这里,模板只为一个字符串,但如果你有一个更复杂的模板,该方法可能就不适用了。通常的解决方案是将模板放在“script”标签中:

1

2

3

<script  type="text/x-mustache" id="template">

    <p>Hello,  {{name}}</p>

  </script>

然后,我们可以访问的script标签的内容。例如,使用jQuery,它很容易实现:

1

2

3

var temp =  $("#template").html();

Mustache.render(temp {  name: "Jack" });

// 返回: <p>Hello, Jack</p>

“script”一个浏览器无法理解的“type”属性,浏览器就会忽略该Script,不将它作为JavaScript,也不会执行它。

你也可在模板中使用循环,如下面这个模板:

1

2

3

{{#people}}

  {{name}}

{{/people}}

传递数据:

1

{ people: [ {  name: "Jack" }, { name: "Fred" } ] }

你将得到“JackFred”字符串。

Mustache还有更多的功能,点击这里查看详情。

2.Underscore Templates

Underscore提供了各种各样的有用的方法,也提供了简单的模板。它的语法与Mustache稍有不同。下面为一个简单案例:

1

2

_.template("Hello, <%=  name %>", { name: "Jack" });

 // 返回:Hello, Jack

如果你曾经使用过Embedded Ruby(缩写为ERB),你就会对该语法更为熟悉。“<%=name%>”表示无论“name”是什么值,都应该输出在“<%=name%>”的位置。Underscore同样有循环与条件语句,但与Mustache同样稍有不同。

1

2

var template  = "<% _.each(people, function(name) { %>  <li><%=   name %></li> <% }); %>"

_.template(template, { people:  ["Jack", "Fred"] } );

Underscore模板中,你可以在“<% %>”是插入任何JavaScript。注意,“<%= %>”用于输出,<% %>用来包含JavaScript。这意味着你在JS中使用的任何形式的循环与条件语句同样可以在Underscore中使用。

了解Underscore更多功能,请点击这里查看。

3.Embedded JS Templates

Embedded JSEJS来源于ERB模板,且与ERB有很多相似之处。它有着与ERB相同的Tag,且包含很多相同的功能。

EJS的特别之处在于,你需要把模板存于单独文件中,并将文件名传递给EJS。它会加载该文件,并返回HTML

1

2

3

4

5

6

// in template.ejs

  Hello, <%= name  %>

 

// in JS file

  new EJS({ url: "template.ejs" }).render({ name: "Jack" });

// 返回: Hello, Jack

注意,你可以加载文本模板:

1

new EJS({ text: "Hello,  <%= name %>" }).render({ name: "Jack" });

下面将介绍如何进行循环,以数组“People”为例,并在网站上链接到他们的个人页面:

1

2

3

4

5

6

7

8

9

10

11

12

// template.ejs

  <ul>

    <% for(var i = 0; i < people.length; i++) { %>

      <li><%=  link_to(people[i], "/profiles/" + people[i])  %></li>

    <% }  %>

  </ul>

 

// in JS file

new EJS({  url: "template.ejs" }).render({ people:  [ "Jack", "Fred" ] })

 

// Each rendered <li> will  look like:

<li><a  href="/profiles/Jack">Jack</a></li>

这与Underscore 有些相似,但要注意“link_to”的使用。它是EJS定义的一个Helper,以便链接更容易使用。

了解更多EJS,请关注EJS官方网站

4.HandlebarsJS

Handlebars为最流行的模板引擎之一,构建于Mustache之上。适用于Mustache模板的功能同样适用于Handlebars模板。同时,Handlebars还增加了很多Helper。其中之一是“With”

1

2

3

4

5

// with this template:

  var source = "{{#with author}} <h2>By  {{firstName}} {{lastName}}</h2> {{/with}}";

  var template = Handlebars.compile(source);

  var html = template({ author: {  firstName: "Jack", lastName: "Franklin" } });

// returns: <h2>By Jack  Franklin</h2>

注意,Handlebars编译器的工作方式略有不同。首先,你把该模板传递给“Handlebars.compile”,它会返回一个函数。你将包含数据的对象传递给该函数,该函数将返回HTML“{#with}}”Helper取得一个对象,并允许你在其中向该对象传递属性。但不是采用以下形式:

1

{{ author.firstName}}  {{author.lastName}}

而是下面这种形式

1

{{#with author}} {{firstName}} {{lastName}}  {{/with}}

这样可以节约输入,尤其当你十分频繁地使用它时。

Handlebars也提供了“each”Helper 

1

2

3

4

var source  = "{{#each people}} {{name}} {{/each}}";

  var template = Handlebars.compile(source);

  var html = template({ people: [{ name: "Jack" }, { name: "Fred" }] });

  //返回: "JackFred"

此外,你还可以使用自己的方法来扩展Handlebars,具体方法可参与该文档

5.Jade templating

随着Node.js的流行及大量Web应用构建于它之上,现在已有很多模板被设计用于服务器端。Jade模板与我们目前为止看到的大不相同,它依靠大量的缩进与空格。下面看一例:

1

2

3

4

5

6

7

8

9

10

// template.jade

  p

    | Hello,

    = name

 

// JS

  jade.renderFile("template.jade",  { name: "Jack" }, function(err, result) {

    console.log(result);

    // logs:  Hello, Jack

  });

首次看到Jade可能会让你不舒服,但你会很快适应它。在“p”下面缩进两个字符,表明这两个字符存在于“p”内。“|”用来告知Jade,该行是需要输出的纯文本;“=”用来告知Jade寻找一个名为“name”的变量。

我们同样可以在Jade中使用循环:

1

2

each person in people

    li=person

调出存储名字的数组:{ people: [ "Jack", "Fred" ]},它将输出:

1

<li>Jack</li><li>Fred</li>

Jade具有很多其他模板所不具有的功能。它也可以做诸如输出Script标签此类的事:

1

script(type="text/javascript",  src="myfile.js")

 

 

原文链接:Thetop 5 JavaScript templating engines

 

The top 5 JavaScript templating engines

Progressions in applicationdevelopment with JavaScript has led to a number of libraries existing tosupport them. Developer Jack Franklin talks through some of the popular templatinglibraries.

Whenyou build a JavaScript application, you'll almost certainly use some JavaScripttemplates. Rather than use a library like jQuery (or vanilla JavaScript) toupdate your HTML when values update, you can use templates, which cleans upyour code hugely. In this article, we'll look at some popular templatinglibraries.

01. Mustache

Mustacheis often considered the base for JavaScript templating

Mustache isoften considered the base for JavaScript templating. Another popular solution,Handlebars, actually builds on top of Mustache, but that doesn't mean that itisn't a very good templating solution. Here's an example:

 Mustache.render("Hello,{{name}}", { name: "Jack" });
   
 //returns: Hello, Jack

OnceMustache is included on your page, you have access to the global 'Mustache'object. The main method you'll use is 'render', which takes two arguments. Thefirst is the actual template, and the second is any arguments that need to bepassed to it.

Inthe above example, you can see I've referenced '{{name}}'. Two braces aroundsomething is the Mustache syntax to show that it's a placeholder. When Mustachecompiles it, it will look for the 'name' property in the object we pass in, andreplace '{{name}}' with the value, which is "Jack", in this case.

HereI've passed in the template as a string, but if you had a more complextemplate, you might not like to do it this way. Instead, a common solution isto place a template inside 'script' tags:

<script type="text/x-mustache"id="template">
   <p>Hello, {{name}}</p>
 </script>

Wecan then access the contents of that script tag. For example, with jQuery it'sas easy as:

var temp = $("#template").html();
 Mustache.render(temp { name: "Jack" });
 
 //returns: <p>Hello, Jack</p>

Bygiving the 'script' tag a 'type' attribute of something the browser doesn'tunderstand, it will ignore the contents, so it doesn't try to execute it asJavaScript.

Youcan also use loops in your templates. Taking this template:

{{#people}}
   {{name}}
 {{/people}}

Withthis data passed in:

{ people: [ { name: "Jack" }, { name: "Fred" }] }

You'llget the string "JackFred" returned.

Mustache is capable of a lot more than coveredhere, so do check the Github README formore.

02. Underscore Templates

Underscoreis a utlity belt library for JavaScript

Underscoreis a utlity belt library for JavaScript, providing all sorts of useful methods.It also provides simple templates we can use. It uses a slightly differetsyntax to Mustache. Here's a simple example:

_.template("Hello, <%= name %>", { name:"Jack" });
  
//returns: Hello, Jack

Ifyou've ever used Embedded Ruby (or ERB for short), you may be more familiarwith this syntax. The '<%= name %>' denotes that whatever the value of`name` should be outputted in place of '<%= name %>'. Underscore can alsodo things like loops and conditionals, but it does it slightly differently tohow Mustache does.

 var template = "<%_.each(people, function(name) { %> <li><%=   name%></li> <% }); %>"
 _.template(template, { people: ["Jack", "Fred"] } );

InUnderscore templates, you can embed arbitary JavaScript within '<% %>'tags. Note that we use '<%= %>' to output to the page, and `<% %>`to contain JavaScript. This means any form of loop or conditional you can do inJS, you can use in Underscore.

You can find out more about Underscore and itscapabilitieshere.

03. Embedded JS Templates

EmbeddedJS (EJS) is inspired by ERB templates

EmbeddedJS (EJS)is inspired by ERB templates and acts much the same. It uses the same tags asERB (and indeed, Underscore) and has many of the same features. It also implementssome Ruby on Rails inspired helpers, which we'll get to shortly.

EJSis different in that it expects your templates to be in individual files, andyou then pass the filename into EJS. It loads the file in, and then gives youback HTML.

// in template.ejs
 Hello, <%= name %>

// in JS file
 new EJS({ url: "template.ejs" }).render({ name: "Jack" });
  
//returns: Hello, Jack

Notethat you can load in text templates, too:

new EJS({ text: "Hello, <%= name %>" }).render({name: "Jack" });

Here'show we would loop over some people, and link to their profile pages on ourwebsite:

// template.ejs
 <ul>
   <% for(var i = 0; i < people.length; i++) { %>
     <li><%= link_to(people[i], "/profiles/" + people[i])%></li>
   <% } %>
 </ul>

// in JS file
 new EJS({ url: "template.ejs" }).render({ people: [ "Jack","Fred" ] })

 // Each rendered <li> will looklike:
  
<li><ahref="/profiles/Jack">Jack</a></li>

That's very similar to how Underscore might doit, but note the use of `link_to`. That's a helper that EJS defines to makelinking a little bit easier. It implements a lot of others too, which aredocumented here.To find out more about EJS, I suggest theEJS home page.

04. HandlebarsJS

Handlebarsis one of the most popular templating engines and builds on top of Mustache

Handlebarsis one of the most popular templating engines and builds on top of Mustache.Anything that was valid in a Mustache template is valid in a Handlebarstemplate, so I won't cover those basics again. Handlebars add lots of helpersto Mustache. One of these is 'with', which is great for working with deepobjects:

// with this template:
  
var source = "{{#withauthor}} <h2>By {{firstName}} {{lastName}}</h2> {{/with}}";
 var template = Handlebars.compile(source);
 var html = template({ author: { firstName: "Jack", lastName:"Franklin" } });
 
 //returns: <h2>By Jack Franklin</h2>

Noticethat the Handlebars compiler works slightly differenly. Firstly, you pass thetemplate into 'Handlebars.compile', which then returns a function. You can callthat, passing in the object containing the data, and then you get the HTMLback. The '{{#with}}' helper takes an object and then within it allows you torefer to properties within that object. This means rather than doing:

 {{ author.firstName}} {{author.lastName}}

Wecan do:

 {{#with author}} {{firstName}} {{lastName}} {{/with}}

Whichcan save on typing, especially if you're doing it a lot.

Handlebarsalso provides an each helper:

var source = "{{#each people}} {{name}} {{/each}}";
 var template = Handlebars.compile(source);
 var html = template({ people: [{ name: "Jack" }, { name:"Fred" }] });

  // returns: "JackFred"

Personally for me, I prefer Handlebars andtend to use it for all my client side templating. It's also very easy to extendHandlebars with your own methods - this documentation isa good place to start.

05. Jade templating

Jadetemplates are very different in that they depend hugely on indents andwhitespace

I'm going to end with something a bitdifferent here - server side templating with Jade.With the popularity of NodeJS and the number of web apps being built in it now,there's a lot of templating libraries out there designed to be used on theserver. Jade templates are very different to any we've looked at so far, inthat it depends hugely on indents and whitespace. Here's a simple example:

// template.jade
  
p
   | Hello,
   = name

// JS
  
jade.renderFile("template.jade",{ name: "Jack" }, function(err, result) {
   console.log(result);
   // logs: Hello, Jack
 });

Jadeis a little jarring to look at at first, but you do get used to it, honest! Weindent the two lines below the 'p' to denote that they exist within it. The '|'is used to tell Jade that what's on that line is just plain text to output, andthe '=' tells Jade to look for a variable named 'name'.

Wecan also do loops in Jade too:

each person in people
   li=person

Calledwith an array of names: '{ people: [ "Jack", "Fred" ]}',this will output:

<li>Jack</li><li>Fred</li>

Jadeis capable of a lot more - unlike the other template engines we've looked at,the idea with Jade is that you write the entire of your HTML in it. It can dothings like output script tags:

script(type="text/javascript",src="myfile.js")

A good place to start is the Jade examples.You can download them and run them with Node to see the output and how Jade works.

Andthat concludes our look at five of the most popular templating engines. There'splenty more out there, but hopefully this should give you a good starting pointto go and find the one that suits you best.

Jack Franklin is a 20-year-old developer living in London, UK. Heruns a JavaScript blog at javascriptplayground.com and also writes PHP, Ruby andother languages. He tweets as@Jack_Franklin.

Also read:

·        Inspiring examples of CSS

·        Top examples of JavaScript

·        The top 20 jQuery plugins

·        CSS and JavaScript tutorials topower up your skills

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值