简体   繁体   中英

Organizing Handlebars files

In this simple example...

http://plnkr.co/edit/78ObAiirrSFPcvyiBKqn

...I try to have a Handlebars template and the content that should populate it into separate files, instead of having the template inside the HTML and the content object in the js script, as in this other example:

http://embed.plnkr.co/KXdVgedRA8K95S17peuH/

And I also found this post where this guy means the same as I do (right?):

Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)

I tried that (what's on the accepted answer, see the code below), but it doesn't work. I get "undefined is not a function".

On the other hand, that answer has 90 upvotes so I must be missing something somewhere. Could someone point that out to me?

Another related question: should I use AJAX to load a local file?

index.html

<script src="cities.tmpl.js"></script> <!-- compiled template -->
<script src="content.js"></script>
<script src="script.js"></script>

script.js

var template = Handlebars.templates['cities.tmpl']; // your template minus the .js
var context  = data_pr.all(); // your data
var html     = template(context);

Solved it, based on this post:

http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/

I changed a little bit so it's easier to read (at least for me):

function getTemplate(path, callback) {
    $.ajax({
        url: path,
            success: function(data) {
                var template = Handlebars.compile(data);     
                if (callback) callback(template);
        }
    });
}

getTemplate('cities.tmpl', function(template) {
    var html = template(data_pr); // data_pr = my data from content.js
    document.getElementById('cities-placeholder').innerHTML = html;
});

sample code here

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