【发布时间】: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文档中(<html><head></head><body>...</body></html>),将每个模板包装在<div id="template-abc"></div>中,然后使用$.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