Underscore 中的外部模板
我使用下划线模板。可以附加外部文件作为模板吗?
在主干视图中,我有:
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>
它运行良好。但是我需要外部模板。 我尝试:
<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 ) })
但它不起作用。
I use Underscore template. It is possible to attach a external file as template?
In Backbone View I have:
textTemplate: _.template( $('#practice-text-template').html() ),
initialize: function(){
this.words = new WordList;
this.index = 0;
this.render();
},
In my html is:
<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">
or
textTemplate: _.template( $('#practice-text-template').load('templates/tmp.js') ),
or
$('#practice-text-template').load('templates/tmp.js', function(data){ this.textTemplate = _.template( data ) })
but it did not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
这是一个简单的解决方案:
这里使用“async: false”并不是一个坏方法,因为无论如何您都必须等到模板被加载。
因此,“渲染”功能
dir
[我正在编辑答案而不是留下评论,因为我认为这很重要。]
如果模板未显示在本机应用程序中,并且您请参阅
HIERARCHY_REQUEST_ERROR: DOM Exception 3
,查看 Dave Robinson 对 到底是什么会导致“HIERARCHY_REQUEST_ERR:DOM异常” 3"-错误?。基本上,您必须添加
到 $.ajax 请求。
Here is a simple solution:
Using "async: false" here is not a bad way because in any case you must wait until template will be loaded.
So, "render" function
dir
[I am editing the answer instead of leaving a comment because I believe this to be important.]
if templates are not showing up in native app, and you see
HIERARCHY_REQUEST_ERROR: DOM Exception 3
, look at answer by Dave Robinson to What exactly can cause an "HIERARCHY_REQUEST_ERR: DOM Exception 3"-Error?.Basically, you must add
to the $.ajax request.
编辑:这个答案已经过时了。我会删除它,但这是“已接受”的答案。我会提出我的意见。
我不会再提倡这样做了。相反,我会将所有模板分成单独的 HTML 文件。有些人建议异步加载这些(Require.js 或某种模板缓存)。这在小型项目上效果很好,但在具有大量模板的大型项目上,您会发现自己在页面加载时发出大量小型异步请求,这是我真的不喜欢的。 (呃...好吧,你可以通过使用 r.js 预编译初始依赖项来使用 Require.js 来解决这个问题,但是对于模板,这对我来说仍然感觉不对)
我喜欢使用grunt 任务 (grunt-contrib-jst) 将所有 HTML 模板编译到单个 templates.js 文件中并包含该文件。在我看来,您可以获得世界上最好的...模板存在于文件中,所述模板的编译在构建时(而不是运行时)发生,并且页面启动时没有一百个微小的异步请求。
下面的所有内容都是垃圾
对我来说,我更喜欢在模板中包含 JS 文件的简单性。因此,我可能会创建一个名为 view_template.js 的文件,其中包含模板作为变量:
然后,就像像普通文件一样包含脚本文件,然后在您的视图中使用它一样简单:
更进一步,我 < em>实际上使用coffeescript,所以我的代码实际上看起来更像这样,并避免行尾转义字符:
使用这种方法可以避免在确实没有必要的地方引入 require.js 。
EDIT: This answer is old and outdated. I'd delete it, but it is the "accepted" answer. I'll inject my opinion instead.
I wouldn't advocate doing this anymore. Instead, I would separate all templates into individual HTML files. Some would suggest loading these asynchronously (Require.js or a template cache of sorts). That works well on small projects but on large projects with lots of templates, you find yourself making a ton of small async requests on page load which I really dislike. (ugh... ok, you can get around it with Require.js by pre-compiling your initial dependencies with r.js, but for templates, this still feels wrong to me)
I like using a grunt task (grunt-contrib-jst) to compile all of the HTML templates into a single templates.js file and include that. You get the best of all worlds IMO... templates live in a file, compilation of said templates happen at build time (not runtime), and you don't have one hundred tiny async requests when the page starts up.
Everything below is junk
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:
Then, it is as simple as including the script file like a normal one and then using it in your view:
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:
Using this approach avoids brining in require.js where it really isn't necessary.
这个mixin允许您以非常简单的方式使用下划线渲染外部模板:
_.templateFromUrl(url, [data], [settings])
。方法API与Underscore的_.template()几乎相同。包括缓存。用法:
This mixin allows you to render external template using Underscore in very simple way:
_.templateFromUrl(url, [data], [settings])
. Method API is almost the same as Underscore's _.template(). Caching included.Usage:
我不想使用 require.js 来完成这个简单的任务,所以我使用了修改后的 koorchik 的解决方案。
为什么将模板附加到文档中,而不是将它们存储在 javascript 对象中?因为在生产版本中我想生成已包含所有模板的 html 文件,所以我不需要发出任何额外的 ajax 请求。同时,我不需要在我的代码中进行任何重构,就像我
在 Backbone 视图中使用的那样。
I didn't want to use require.js for this simple task, so I used modified koorchik's solution.
Why to append templates to document, rather than storing them in javascript object? Because in production version I would like to generate html file with all templates already included, so I won't need to make any additional ajax requests. And in the same time I won't need to make any refactoring in my code, as I use
in my Backbone views.
这可能有点偏离主题,但您可以使用 Grunt (http://gruntjs.com/) - 它在 node.js 上运行(http://nodejs.org/,可用于所有主要平台)来从命令行。这个工具有很多插件,比如模板编译器,https://npmjs.org/package/grunt-contrib -jst。请参阅 GitHub 上的文档,https://github.com/gruntjs/grunt-contrib-jst。 (您还需要了解如何运行节点包管理器,https://npmjs.org/。别担心,这非常简单然后,
您可以将所有模板保存在单独的 html 文件中,运行该工具以使用下划线预编译它们(我相信这是 JST 插件的依赖项,但不用担心,节点包管理器会自动安装依赖项)为你)。
这会将所有模板编译为一个脚本,例如
加载脚本将设置一个全局 - 默认情况下为“JST” - 这是一组函数,可以像这样访问:
JST['templates/listView.html' ]()
类似
这与您将该脚本标记的内容放入 (templates/)listView.html 中
。但是,真正的亮点是:Grunt 附带了这个名为“watch”的任务,该任务基本上将监视您对文件的更改已在本地 grunt.js 文件中定义(这基本上是您的 Grunt 项目的配置文件,用 JavaScript 编写)。如果您让 grunt 为您启动此任务,请在
命令行中键入:,Grunt 将监视您对文件所做的所有更改,并在检测到更改时自动执行您在 grunt.js 文件中为其设置的所有任务- 就像上面描述的jst任务。编辑并保存文件,所有模板都会重新编译为一个 js 文件,即使它们分布在多个目录和子目录中。
可以配置类似的任务来检查 javascript、运行测试、连接和缩小/丑化脚本文件。所有这些都可以与监视任务相关联,因此对文件的更改将自动触发项目的新“构建”。
设置并了解如何配置 grunt.js 文件需要一些时间,但它非常非常值得投入时间,而且我认为您永远不会回到 grunt 之前的工作方式
This might be slightly off topic, but you could use Grunt (http://gruntjs.com/) - which runs on node.js (http://nodejs.org/, available for all major platforms) to run tasks from the command line. There are a bunch of plugins for this tool, like a template compiler, https://npmjs.org/package/grunt-contrib-jst. See documentation on GitHub, https://github.com/gruntjs/grunt-contrib-jst. (You will also need to understand how to run node package manager, https://npmjs.org/. Don't worry, it's incredibly easy and versatile. )
You can then keep all your templates in separate html files, run the tool to precompile them all using underscore (which I believe is a dependency for the JST plugin, but don't worry, node package manager will auto install dependencies for you).
This compiles all your templates to one script, say
Loading the script will set a global - "JST" by default - which is an array of functions, and can be accessed like so:
JST['templates/listView.html']()
which would be similar to
if you put the content of that script tag in (templates/)listView.html
However, the real kicker is this: Grunt comes with this task called 'watch', which will basically monitor changes to files that you have defined in your local grunt.js file (which is basically a config file for your Grunt project, in javascript). If you have grunt start this task for you, by typing:
from the command line, Grunt will monitor all changes you make to the files and auto-execute all tasks that you have setup for it in that grunt.js file if it detects changes - like the jst task described above. Edit and then save your files, and all your templates recompile into one js file, even if they are spread out over a number of directories and subdirectories.
Similar tasks can be configured for linting your javascript, running tests, concatenating and minifying / uglifying your script files. And all can be tied to the watch task so changes to your files will automatically trigger a new 'build' of your project.
It takes some time to set things up and understand how to configure the grunt.js file, but it well, well worth the time invested, and I don't think you will ever go back to a pre-grunt way of working
我认为这可能会对您有所帮助。解决方案中的所有内容都围绕
require.js
库,它是一个 JavaScript 文件和模块加载器。上面链接中的教程很好地展示了如何组织骨干项目。还提供了示例实现。希望这有帮助。
I think this is what might help you. Everything in the solution revolves around
require.js
library which is a JavaScript file and module loader.The tutorial at the link above shows very nicely how a backbone project could be organized. A sample implementation is also provided. Hope this helps.
我对 javascript 模板很感兴趣,现在我正在用骨干迈出第一步。这是我想出的并且看起来效果很好。
I got interested on javascript templating and now I'm taking the first steps with backbone. This is what i came up with and seems to work pretty well.
我必须将数据类型设置为“文本”才能使其适合我:
I had to set the data type to "text" to make it work for me:
我找到了一个适合我的使用 jQuery 的解决方案。
我使用 jQuery.load() 方法将下划线模板代码添加到主 html 文件中。
一旦它出现,我就用它来生成模板。
一切都需要同步发生!
概念是:
我有一个下划线地图模板代码:
我将该代码放入名为map-template.html的文件中,
然后为模板文件创建一个包装器。
然后我将该文件包含在我的主 html 文件中,如下所示。
心里:
干杯。
I found a solution that works for me with using jQuery.
I add the underscore template code, with jQuery.load() method, to the main html file.
Once it's there, I'm using it for generating the templates.
All need to happen synchronously!
The concept is:
I have a underscore map template code:
And I put that code in a file called map-template.html
After that I create a a wrapper for the template files.
Then I include that file in my main html file like so.
In head:
Cheers.
我知道这个问题确实很老,但它是谷歌搜索下划线 ajax 模板的第一个结果。
我厌倦了找不到一个好的解决方案,所以我创建了自己的解决方案:
https:// github.com/ziad-saab/underscore-async-templates
除了使用 AJAX 加载下划线模板外,它还添加了 <% include %> 。功能。我希望它对某人有用。
I know this question is really old but it came up as the first result on a google search for underscore ajax templates.
I was tired of not finding a good solution for this so I created my own:
https://github.com/ziad-saab/underscore-async-templates
In addition to loading underscore templates using AJAX, it adds <% include %> functionality. I hope it can be useful to someone.
我对强制 jQuery 同步运行感到有点不安,所以我使用 Promise 修改了前面的同步示例。它几乎相同,但异步运行。我在这个例子中使用 hbs 模板:
然后使用渲染的 html:
注意:正如其他人所讨论的,最好将所有模板编译到单个 templates.js 文件中并在开始时加载它,而不是有许多小模板网页加载时同步 AJAX 调用获取模板。
I was a bit uneasy forcing jQuery to function synchronously, so I modified the previous synchronous example using promises. It's pretty much the same, but runs asynchronously. I'm using hbs templates in this example:
Then to use the rendered html:
NOTE: As discussed by others, it would be preferable to compile all templates into a single templates.js file and load that in the beginning rather than have many small synchronous AJAX calls to get templates when the webpage loads.
转发警告 - 这里是龙:
我提到下面所示的方法只是为了帮助那些努力使 ASP.NET 堆栈(和类似框架)与 js-libs 生态系统和谐工作的人。不用说,这不是一个通用的解决方案。话虽如此...
/endforwardwarning
如果您使用 ASP.NET,您只需将模板放置在自己的一个或多个部分视图中即可将其外部化。又名在你的 .cshtml 中:
在你的 template.cshtml 中:
现在你可以像往常一样使用模板:
希望这种难以捉摸的明显方法可以帮助人们节省一个小时的时间。
Forward warning - Here be dragons:
I mention the approach shown below simply to help those struggling to make ASP.NET stacks (and similar frameworks) work harmoniously with the ecosystem of js-libs. It goes without saying that this is not a generic solution. Having said that ...
/endforwardwarning
If you are using ASP.NET you can externalize your templates simply by placing them inside one or more partial views of their own. Aka inside your .cshtml:
Inside your template.cshtml:
And now you can use the template like usual:
Hope this elusively-obvious approach helps someone save an hour's worth of head-scratching.