在下划线外部模板 [英] External template in Underscore

查看:95
本文介绍了在下划线外部模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下划线模板。它可以附加一个外部文件作为模板

I use Underscore template. It is possible to attach a external file as template?

在主干查看我有:

 textTemplate: _.template( $('#practice-text-template').html() ),

 initialize: function(){                                            
  this.words = new WordList;            
  this.index = 0;
  this.render();
 },

在我的HTML是:

<script id="practice-text-template" type="text/template">
   <h3>something code</h3>
</script>

它运作良好。但我需要外部模板即可。
我尝试:

It works well. But I need external template. I try:

<script id="practice-text-template" type="text/template" src="templates/tmp.js">

textTemplate: _.template( $('#practice-text-template').load('templates/tmp.js') ),

$('#practice-text-template').load('templates/tmp.js', function(data){ this.textTemplate = _.template( data ) })

但它没有工作。

非常感谢您的帮助。
汤姆

Thanks a lot for Your help. Tom

推荐答案

编辑:这个答案是陈旧过时。我想删除它,但它是接受的答案。我会代替注入我的意见。

我不提倡再这样做。相反,我会单独所有模板成单独的HTML文件。有些人会建议加载这些异步(Require.js或某种形式的模板缓存)。行之有效的小项目,但是,有很多的模板大项目,你会发现自己做一吨在页面加载小异步请求,我真的不喜欢的。 (呃...好吧,你可以通过pre-编译与r.js最初的依赖,但对于模板,这仍然觉得我错了绕过它与Require.js)

我喜欢用一个咕噜任务(咕噜-的contrib-JST)所有的HTML模板编译成一个单一的templates.js文件,包括。你得到了世界上最好的IMO ...模板住在一个文件中,编译所述模板发生在编译​​时(而不是运行时),你没有百微小的异步请求页面时启动。

下面的一切都是垃圾

对于我来说,我preFER包括我的模板的JS文件的简单性。所以,我可能会创建一个名为view_template.js文件,其中包括模板作为一个变量:

For me, I prefer the simplicity of including a JS file with my template. So, I might create a file called view_template.js which includes the template as a variable:

app.templates.view = " \
    <h3>something code</h3> \
";

然后,它是为包括像一个正常的一个脚本文件,然后在您的视图用它作为简单的:

Then, it is as simple as including the script file like a normal one and then using it in your view:

template: _.template(app.templates.view)

把它更进了一步,我的真正的使用CoffeeScript的,所以我的code其实看起来更像是这一点,避免尾线的转义字符:

Taking it a step further, I actually use coffeescript, so my code actually looks more like this and avoid the end-of-line escape characters:

app.templates.view = '''
    <h3>something code</h3>
'''

使用这种方法避免了在require.js它真的是没有必要的盐渍。

Using this approach avoids brining in require.js where it really isn't necessary.

这篇关于在下划线外部模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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