【问题标题】:How to store multiple html templates in one file?如何将多个html模板存储在一个文件中?
【发布时间】:2014-05-11 16:19:10
【问题描述】:

我只知道一种通过 underscore.js 定义模板的方法,它看起来像这样:

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

这样,在每个模板的头部添加一个脚本标签对我来说看起来很讨厌。我只想要一个外部文件来存储所有 html 模板,并在需要时加载文件的特定部分。

例如;我的文件是“templates.file”,它包含所有模板:

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

是否可以在不加载除主干.js 和下划线.js 之外的任何其他框架的情况下做到这一点?哪种语法适合这种文档?最重要的是,我如何加载和查看 templates.file 的一部分,例如仅联系部分?

【问题讨论】:

  • 尝试将templates.file命名为templates.html,将整个文件包装在完整的html文档中(&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt;),将每个模板包装在&lt;div id="template-abc"&gt;&lt;/div&gt;中,然后使用$.get('/path/to/templates.html #template-abc', function(html) { alert(html); })异步加载(需要空间在 URL 和 id 之间)
  • @colllin 你对“html”扩展名是正确的。但不幸的是我意识到$.get 函数不支持选择器定义。只有$.load 会这样做,它会将内容加载到 div 而不是变量中。当我们想将 html 文档的任何部分加载到变量中时,我们必须调用 ajax 函数,然后通过filter 选择 div。详情请看我的回答。顺便说一句,这是个好建议。
  • 如果有什么好的建议请点赞。
  • @colllin 我需要代表投票抱歉。

标签: jquery templates backbone.js underscore.js


【解决方案1】:

在尝试了许多可能性之后,我编写了一段我需要的代码。我必须回答我的问题,因为有人可能需要它。这是我如何在一个外部 html 文件中收集多个模板,然后在需要时将它们加载到我的脚本文件中。

模板.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>

还有我的脚本:

$.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();

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多