`
haohappy2
  • 浏览: 327591 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Top 5 JS template

    博客分类:
  • JS
 
阅读更多

Progressions in application development with JavaScript has led to a number of libraries existing to support them. Developer Jack Franklin talks through some of the popular templating libraries.

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

01. Mustache

JavaScript templatesMustache is often considered the base for JavaScript templating

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

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

Once Mustache 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. The first is the actual template, and the second is any arguments that need to be passed to it.

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

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

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

We can then access the contents of that script tag. For example, with jQuery it's as easy as:

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

By giving the 'script' tag a 'type' attribute of something the browser doesn't understand, it will ignore the contents, so it doesn't try to execute it as JavaScript.

You can also use loops in your templates. Taking this template:

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

With this data passed in:

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

You'll get the string "JackFred" returned.

Mustache is capable of a lot more than covered here, so do check the Github README for more.

02. Underscore Templates

JavaScript templatesUnderscore is a utlity belt library for JavaScript

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

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

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

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

In Underscore 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 in JS, you can use in Underscore.

You can find out more about Underscore and its capabilitieshere.

03. Embedded JS Templates

JavaScript templatesEmbedded JS (EJS) is inspired by ERB templates

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

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

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

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

Note that you can load in text templates, too:

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

Here's how we would loop over some people, and link to their profile pages on our website:

// 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>

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

04. HandlebarsJS

JaveScript TemplatesHandlebars is one of the most popular templating engines and builds on top of Mustache

Handlebars is 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 Handlebars template, so I won't cover those basics again. Handlebars add lots of helpers to Mustache. One of these is 'with', which is great for working with deep objects:

// 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>

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

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

We can do:

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

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

Handlebars also 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 and tend to use it for all my client side templating. It's also very easy to extend Handlebars with your own methods - this documentation is a good place to start.

05. Jade templating

JavaScript templatesJade templates are very different in that they depend hugely on indents and whitespace

I'm going to end with something a bit different 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 the server. Jade templates are very different to any we've looked at so far, in that 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
  });

Jade is a little jarring to look at at first, but you do get used to it, honest! We indent 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, and the '=' tells Jade to look for a variable named 'name'.

We can also do loops in Jade too:

each person in people
    li=person

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

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

Jade is 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 do things 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.

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

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

分享到:
评论

相关推荐

    template .rar

    JavaScript可以动态改变图片的`left`和`top`属性,使其在页面上移动。CSS3则可以通过`transform`属性配合`translateX`和`translateY`来实现平移效果。 2. **图片缩放**:同样,图片缩放可以通过JavaScript或CSS3来...

    html5 个人网站源码

    `js`目录可能包含JavaScript代码,这是网页动态功能的关键。HTML5提供了新的API,如Geolocation用于获取用户位置,Web Storage(localStorage和sessionStorage)用于在浏览器端存储数据,Web Workers实现后台处理以...

    提示对话框-消息提示通知插件spop.js-找优质资源尽在【蓝文资源库】bluestep.cc.zip

    spop.js是一款纯js toast消息提示通知插件。通过spop.js插件,你可以快速的在网页上制作出漂亮的toast消息提示效果。该js toast消息提示插件的特点还有: 内置4种主题样式:default, success, warning, error。 ...

    原生JS经典小项目-网页布局

    2. **Grid布局**:类似地,JS也可以操作CSS Grid属性,如`grid-template-columns`和`grid-template-rows`,实现动态的网格布局。通过`.style.gridTemplateColumns`和`.style.gridTemplateRows`,可以在运行时创建或...

    【JavaScript源代码】vue添加自定义右键菜单的完整实例.docx

    Vue.js 是一个流行的前端框架,用于构建用户界面。在JavaScript中,右键菜单通常是通过原生浏览器事件来实现的,而在Vue中,我们可以通过监听原生事件或使用第三方插件来创建自定义的右键菜单。以下是使用Vue实现...

    html5-yuansu.rar_h5周期表_h5超炫元素表_html yuansu_www.5/yuansu.com_元素周期

    这个"html5-yuansu.rar"压缩包中的"html5-元素周期表"可能包含动画效果,比如粒子分布,这可能通过CSS3动画或JavaScript实现,使得用户在浏览时能体验到卡片漂浮式的动态视觉效果。这种互动性的设计不仅增加了学习的...

    【JavaScript源代码】vue3.0自定义指令(drectives)知识点总结.docx

    template: `&lt;div class="box" v-abs-top="num"&gt;&lt;/div&gt;`, }); app.directive('absTop', (el, binding) =&gt; { el.style.top = binding.value + 'px'; }); ``` 其中,`binding.value`用于获取`v-abs-top`指令...

    vue.js表格实现表头首行固定代码.zip

    Vue.js是一款轻量级的前端JavaScript框架,以其易用性和灵活性深受开发者喜爱。在处理这种复杂布局时,Vue.js提供了多种解决方案。 首先,我们需要一个基础的Vue组件结构来承载我们的表格。组件通常包含`template`...

    【JavaScript源代码】vue手写加载动画项目.docx

    top: 5px; left: 5px; right: 5px; bottom: 5px; border-radius: 50%; /* background: green; */ border: 3px solid transparent; border-top-color: #fff; -webkit-animation: spin 8s linear infinite; ...

    红色幻灯精致的商业网站模板4134_html网站模板_网页源码移动端前端_H5模板_自适应响应式源码.zip

    在压缩包内的“template_292_red_top”文件很可能是这个模板的主要部分,可能包含了HTML文件、CSS文件和JavaScript文件。HTML文件将定义网页的基本结构和内容,CSS文件将负责样式设定,而JavaScript文件将处理动态...

    vue,原生js左右无缝滚动

    Vue.js是一个流行的前端框架,它允许开发者构建可复用、可维护的组件,而原生JavaScript则是其背后的基石,为实现动态交互提供了基础。 首先,让我们了解一下无缝滚动的基本原理。无缝滚动通常通过监听鼠标事件,...

    鼠标经过样式js实现

    JavaScript(JS)作为客户端脚本语言,可以灵活地实现各种动态效果,包括鼠标经过样式。下面我们将深入探讨如何使用JavaScript来实现鼠标经过时的方格下拉样式。 首先,我们需要理解HTML的基础结构,通常一个方格...

    JS网格图片拖拽位置变换效果.zip

    在本文中,我们将深入探讨如何实现一个JS网格图片拖拽位置变换效果,这涉及到HTML、CSS和JavaScript的基础知识,特别是事件处理和DOM操作。首先,我们需要理解标题和描述中的关键概念。 标题"JS网格图片拖拽位置...

    基于 VueJS popover 组件的 popper.js.zip

    vue-popperjs 基于popper.js的 VueJS popover 组件例子jsFiddle安装内容分发网络 (CDN)推荐...(ECMAScript 2015)&lt;template&gt; &lt;popper trigger="clickToOpen" :options="{ placement: 'top', modifiers: { of

    PA网站模板——TAB选项卡制作

    padding-top: 5px; background: url(/images/diy/template_tab_title_over.jpg) no-repeat left bottom; font-weight: bold; color: #ffffff; cursor: pointer; } .template_tab_title_1 { float: left; ...

    五子棋(CSS + JavaScript + jQuery)

    const row = Math.floor((event.clientY - rect.top) / rect.height); const col = Math.floor((event.clientX - rect.left) / rect.width); return { row, col }; } ``` 总的来说,这个五子棋项目结合了CSS的...

    【JavaScript源代码】vue 动态生成拓扑图的示例.docx

    在Vue.js应用中动态生成拓扑图是一种常见的需求,特别是在数据可视化、系统监控等领域。本示例介绍如何在Vue项目中实现横向拓扑图的创建,主要依赖于 Tencent 的 bkTopology 库。以下是对实现这一功能的关键步骤和...

    elements-amp-material-mobile-google-amp-mobile-template-YDVF85-2019-04-26.zip

    在“elements-amp-material-mobile-google-amp-mobile-template-YDVF85-2019-04-26.zip”这个压缩包中,包含的是一个Google AMP的手机端精美模板。"elements-amp-material-mobile"这部分可能指的是该模板采用了...

    【JavaScript源代码】vue backtop组件的实现完整代码.docx

    ```javascript export default { name: "backTop", data() { return { firstShow: false, // 初始化隐藏组件 isHide: false, scrollFLag: true, } }, created() { document.addEventListener('scroll', ()...

Global site tag (gtag.js) - Google Analytics