1

正如在任何项目中所预期的那样,我 90% 的主 HTML 文件由许多不同的模板组成,就像这样:

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

我想把它们放在其他地方,这样用户体验人员就可以自己处理它们了。将它们放在另一个文件中很容易,但是我以后如何导入它们呢?我已经尝试过了,但是浏览器尝试,当然,失败了,将其解释为 javascript 代码。type="text" 也失败了。任何的想法?

谢谢!

4

2 回答 2

2

我使用具有文本插件的模块加载器(requireJS)。它允许您将模板文件定义为参数并在主干视图中使用。

带有 require 的主干视图看起来像这样。

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

除此之外,使用下划线_.template()很容易插入值。

说我的 templateFileName.html 看起来像这样

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

您所要做的就是传递带有这些属性名称的散列来填充 html。

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

$(this.el).html(this.template(myHash));
于 2012-08-16T01:29:55.560 回答
0

怎么样:

if (!async) async = false;
$.ajax({
    async: async,
    url: '/template/' + templateId,
    dataType: 'json',
    success: function(response) {
        $('body').append(response.content);
    }
});
于 2012-08-17T01:29:46.157 回答