1

As is in any project expected, 90% of my main HTML file is composed of many different templates, just like this:

<script type="text/template" id="template-parametros">
  <div id="parametros">
    <h2>Parâmetros</h2>
    <table id="tab-parametros">
      <tr><td>Descrição</td><td>Tipo</td><td>Locale</td></tr>
    </table>
    <button id="parametros-ad">Adicionar</button>
  </div>
</script>

I'd like to put them elsewhere, so the UX guys can work on them on their own. Putting them in another file is easy, but how can I import them later? I've tried but then the browser tries, and, of course, fails, to interpret it as javascript code. type="text" also fails. Any idea?

Thank you!

konr
  • 2,545
  • 2
  • 20
  • 38
  • Duplicated? http://stackoverflow.com/questions/8366733/external-template-in-underscore | http://stackoverflow.com/questions/9834714/external-html-template-for-underscore-js-and-backbone-js | http://stackoverflow.com/questions/8594295/use-one-large-external-file-for-many-javascript-templates-with-backbone-js – fguillen Aug 16 '12 at 07:57

2 Answers2

2

I use a module loader (requireJS) which has a text plugin. It allows you to define your template file as an argument and use inside the Backbone View.

A Backbone View with require looks something like this.

define([
    'jquery',
    'underscore',
    'backbone',
    'text!/templates/templateFileName.html'  // Define the template using text! plugin
], function($, _, Backbone, myTemplate) {  // Include the template as an argument
    "use strict";

    ViewName = Backbone.View.extend({
        template: _.template(myTemplate),  // Setup my template (underscore)
        events: {
            ...
        },
        initialize: function() {
            ...     
        },
        render: function() {
            $(this.el).html(this.template()); // render the template
            return this;
        }
    });

    return ViewName;
});

To add to this, using underscore's _.template() it's easy to interpolate values.

Say my templateFileName.html looks like this

<section>
    <div>
        <%= name %>
    </div>
    <div>
        <%= age %>
    </div>
</section>

All you have to do is pass in the hash with those property names to populate the html.

var myHash = {"name":"Felix", "age":"9"};

$(this.el).html(this.template(myHash));
jmk2142
  • 8,581
  • 3
  • 31
  • 47
0

how about:

if (!async) async = false;
$.ajax({
    async: async,
    url: '/template/' + templateId,
    dataType: 'json',
    success: function(response) {
        $('body').append(response.content);
    }
});
user3335966
  • 2,673
  • 4
  • 30
  • 33
lecstor
  • 5,619
  • 21
  • 27