如何导入一个完整的下划线模板文件? [英] How can I import a file full of Underscore templates?

查看:100
本文介绍了如何导入一个完整的下划线模板文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如预料中的任何项目,我的主HTML文件的90%是由许多不同的模板,就像这样:

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>

我想将它们放在其他地方,所以UX家伙可以对自己对他们的工作。把他们在另一个文件中很容易,但我怎么能稍后导入这些?我试过但随后的浏览器尝试,并且,当然,失败,国米preT它作为JavaScript的code。 TYPE =文本也会失败。任何想法?

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?

感谢您!

推荐答案

我使用的具有文本插件模块加载程序(requireJS)。它允许您定义模板文件作为参数,并骨干视图中使用。

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.

说我templateFileName.html看起来像这样

Say my templateFileName.html looks like this

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

所有你所要做的哈希值传递这些属性名称来填充HTML。

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

这篇关于如何导入一个完整的下划线模板文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆