Question

I only know one way to define templates via underscore.js and it looks like that:

<script type="text/template" class="about">
    <h1><%- about.title %></h1>
    <p><%- about.content %></p>
</script>

<script type="text/template" class="work">
    <h1><%- work.title %></h1>
    <p><%- work.content %></p>
</script>

<script type="text/template" class="contact">
    <h1><%- contact.title %></h1>
    <p><%- contact.content %></p>
</script>
...

This way, adding a script tag to the head for every template is looking nasty to me. I want only one external file to store all html templates in it and load a specific part of the file when i need it.

For example; my file is "templates.file" and it contains all templates:

<!-- About Template -->
<h1><%- about.title %></h1>
<p><%- about.content %></p>

<!-- Work Template -->
<h1><%- work.title %></h1>
<p><%- work.content %></p>

<!-- Contact Template -->
<h1><%- contact.title %></h1>
<p><%- contact.content %></p>

Is it possible to do that without loading any other framework except backbone.js and underscore.js? Which syntax is suitable for this kind of document? And most importantly, how can i load and view a part of templates.file such as only contact section?

Was it helpful?

Solution

After trying many posibilities, i write a piece of code that i need. I have to answer my question because someone can need it. Here is how i collect multiple templates in one external html file and then load them in my script file when i need.

templates.html

<html>
<head>
</head>
<body>
    <script type="html/template" id="about">
        <h3><%= title %></h3>
    </script>

    <script type="html/template" id="contact">
        <h3><%= title %></h3>
    </script>
</body>
</html>

and my script:

$.ajax({
  url: "templates.html",
  dataType: "html",
  async: false,
  success: function(data) {
    // we have to use "filter" instead of "find", "find" is failing
    // we can use underscore's unescape method for &amp;, &lt;, &gt;, &quot;
    contactTemplate = _.unescape($(data).filter("#contact").html());
  }
});

var AppView = Backbone.View.extend({
  el: '#container',
  template: _.template(contactTemplate),
  initialize: function(){
    this.render();
  },
  render: function(){
    this.$el.html(this.template({title: 'Contact'}));
  }
});
var appView = new AppView();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top