将jquery模板放在外部文件中

时间:2011-09-22 00:00:17

标签: jquery templates

我在我的网站上使用jQuery模板,我想将它们全部放在一个单独的文件中。它是怎么做到的?

这是一个例子

      <script type="text/template" id="request-template">......</script>

2 个答案:

答案 0 :(得分:2)

如果您的应用程序很大,我建议您查看require.jstext plugin

结合使用

require.js允许您在需要时动态加载脚本, text插件非常适合加载文本内容文件,就像在javascript模块上使用它一样。因此,您可以将模板放在单独的文件中,并将它们列为javascript的依赖项,然后在javascript需要时加载它们。

修改 简单的解决方案:将脚本块放在一个单独的html文件中,使用jquery加载它们。

separatefile.html

<script type="text/template" id="user-template">user content here...</script>
<script type="text/template" id="form-template">form content here...</script>
<script type="text/template" id="mail-template">mail content here...</script>

你的剧本:

$(function(){
  $('#templates').load("/separatefile.html", function(){
    // handle everything after you have your templates loaded...
  });
});

答案 1 :(得分:0)

包含与其他任何文件一样的JavaScript文件?