简体   繁体   中英

Backbone.js Move script/template information into js file

I have the follow block of code in my HTML as the template that I am using for my Backbone. However, I am not sure how I can move this into a JS file so I will not have the inline javascript in my HTML file. There are some issues that I am encountering when using such in a .erb file and I would like to move the javascript portion into a javascript file and unfortunately I do not know how I can change the script type into a javascript type while keeping it my template.

<script type="text/template" id="lesson-template">
    <span id="lesson-title"><%= tracks[0].title %></span>
    <select class="sel">
        <% _.each(tracks, function(track) { %>
            <option value="<%= track.id %>"><%= track.title %></option>
        <% }); %> 
    </select>
    <p id="tracktext"><%=  tracks[0].text %></p>
</script>

Help is appreciated!

Assuming that you've included underscore, it's pretty simple. Something like this:

var template = _.template(
    '<span id="lesson-title"><%= tracks[0].title %></span>' +
    '<select class="sel">' +
        '<% _.each(tracks, function(track) { %>' +
            '<option value="<%= track.id %>"><%= track.title %></option>' +
        '<% }); %>' + 
    '</select>' +
    '<p id="tracktext"><%=  tracks[0].text %></p>'
);

Then, just access it from the template variable.

Moving templates to javascript codes has many drawbacks: ugly concatenation, code that is essentially presentational interwined with functional code.

If the root of your problem is conflicts with erb you can either :

  • not use erb server side. Do you really need it to output your JS templates ?
  • redefine undercore _.template opening and closing tags

If you go for the second option, all necessary information is available in _.template documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM