How can I import a file full of Underscore templat

2019-08-03 22:39发布

问题:

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!

回答1:

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));


回答2:

how about:

if (!async) async = false;
$.ajax({
    async: async,
    url: '/template/' + templateId,
    dataType: 'json',
    success: function(response) {
        $('body').append(response.content);
    }
});