Pregunta

When I use jQuery to refer to a script ...

var template = _.template( $('#homeTemplate').html(), args );

... it works, but only when the script is in <head> like this ...

<script type="text/template" id="homeTemplate">
    <div class="homePage">
        <% /* stuff */ %>       
    </div>
</script>

If I move it to an external file like this ...

<script src="js/templates/hometemplate.js" type="text/template" id="homeTemplate"></script>

It stops working. Why? And how do I fix this?

¿Fue útil?

Solución

I can see where the confusion is coming from - The only reason template content is typically put in a script tag is because that prevents browser from accidentally generating that HTML in the DOM.

Including js/templates/hometemplate.js will not generate an DOM element that you can select using jQuery. Use AJAX instead to grab the content from js/templates/hometemplate.js:

$.ajax({
    url : 'js/templates/hometemplate.js' 
}).done(function(data) { 
    _.template(data,args);
});

Otros consejos

The second method doesn't work as homeTemplate's innerHTML is an empty string. The solution is using the first working method or loading the template via Ajax.

The <script> template hack, is used to include "NON-HTML" inside a HTML document. If you don't want to have it embed in your HTML, don't use <script>.

There is only fews ways to get a template, a string too long, to your Javascript, there are pros and cons.

  • hidden element
  • <script> hack
  • AJAX
  • long inline Javascript string
  • yet coming new <template> tag, (not even browser supported)

BTW. why do you want your template not being embed in HTML which introduce additional round-trip-latency-delay when templates is supposed to be small (compare with full HTML)?

You could grab them using AJAX. However, I like to keep them organized in a single JS file like:

 Templates = {};

 Templates.myTemplate = [
   "<section>",
         "<article><% /* stuff */ %></article>",
   "</section>"
   ].join( '\n' );

Templates object can then be a property on the global app object app.Templates

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top