Use Underscore.js's template to separate the Backbone.js JS code from the HTML code

Source: Internet
Author: User
Tags code tag php template

This period of time in the process of learning require.js and backbone.js, found that some of the project's HTML code is written in the view of the JS code inside, when the rendering needs to loop on the collection, and then the HTML code splicing up, which seems to be not a very good thing, because the JS generation Code and HTML code together will increase the difficulty of maintenance, and this process takes into account the performance factors, you need to put the HTML code in an array, and finally splicing, the code is more cumbersome to write. After I saw their code, I was thinking about whether there was something like a php template engine that could pass collection in and render it.

I consulted Backbone.js's Handbook http://backbonejs.org/#View-template, which contained a text:

However, we suggest choosing a nice JavaScript templating library. Mustache.js, Haml-js, and Eco is all fine alternatives. Because Underscore.js is already on the page, _.template are available, and is a excellent choice if you prefer simple int Erpolated-javascript style templates.

Whatever Templating strategy you end up with, it's nice if you never has to put strings of HTML in your JavaScript.

It is recommended that we use JS Template Library, and just backbone.js strongly dependent on underscore.js so underscore.js has been introduced, it provides a _.template method, this method supports the use of embedded JS Code HTML template Code, In the JS code does not appear HTML code is a very nice thing! This is in line with our MVC idea, the front-end HTML code is also easy to maintain, otherwise it really becomes spaghetti code!

A description of Underscore.js's template is in the http://underscorejs.org/#template, and here's how you can use it.

Template functions can both interpolate variables, using <%= ...%>, as well as execute arbitrary JavaScript code, wit H <% ...%>. If you wish to interpolate a value, and has it being html-escaped, use <%-...%>

The above text tells us in this template code inside the JS embedded code tag How to use, next I give an example:

We'll build a template, located at: template/album/index.html

?
1234567891011121314151617181920212223242526272829 <%var title = ‘My albums‘;document.title = title;%><h1><%= title %></h1><p>    <a href="album-rest/add">Add new album</a></p><table class="table"><thead>    <tr>        <th>Title</th>        <th>Artist</th>        <th> </th>    </tr></thead><tbody id="album-list"><% _.each(albums, function(album) { %><tr class="album-row">    <td><%= album.get(‘title‘) %></td>    <td><%= album.get(‘artist‘) %></td>    <td>        <a href="album-rest/edit/<%= album.get(‘id‘) %>">Edit</a>        <a href="album-rest/delete/<%= album.get(‘id‘) %>">Delete</a>    </td></tr><% }); %></tbody></table>

The code snippet below defines a backbone View,sync property that asks the server to get all the album data, and then stores the data in the collection of Albumlist. The Render method is then executed, in render inside This.template = _.template (albumtpl, albums); This code is used to complete the work of mixing data and templates, Albumtpl from Template/album /index.html, you must also have all the model in the collection in the form of an array to be assigned to albums, unless you are in the template and collection parsing operation, otherwise you can not only pass in a collection, because Underscore.js's The template is an object structure that does not recognize Backbone.js's collection.

?
1234567891011121314151617181920212223242526 define(["model/album", "collection/album-list", "text", ‘text!template/album/index.html‘], function(Album, AlbumList, text, AlbumTpl) {    var IndexView = Backbone.View.extend({        model : Album,        initialize: function() {        },        sync : function (render) {            var albumList = new AlbumList;            var view = this;            Backbone.sync(‘read‘, albumList, {                success : function (result) {                    albumList.add(result.ret);                    view.collection = albumList;                    view.render();                }            });        },        render: function() {            albumList = this.collection;            albums = albumList.models;            console.log(_.template(AlbumTpl, albums));            this.template = _.template(AlbumTpl, albums);            $("#page-wrapper").html(this.template);        }    });    return IndexView;});

Through the above operation, you can implement the JS code and HTML code separation.

Http://www.tonitech.com/2160.html

Use Underscore.js's template to separate Backbone.js's JS code from the HTML code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.