使用模板RequireJS(text.js插件)和下划线 [英] Templating using RequireJS (text.js plugin) and Underscore

查看:377
本文介绍了使用模板RequireJS(text.js插件)和下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要的最佳方式有些意见在下划线来管理模板。我建立一个应用骨干,并使用下划线来管理模板。我做一个'template.js'文件是这样开始了。

Need some opinions on the best way to manage templating in Underscore. I'm building a Backbone app and using Underscore to manage the templates. I started off by doing something like this in a 'template.js' file.

templates = {
    template1: '<h1>Some HTML</h1>',
    template2: '<h1>Some more HTML and a <%= variable %></h1>
    ...
}

这就会变得混乱。快速。所以,我看着RequireJS的文本插件,这使得它更清洁。现在,我有一堆的HTML文件,我基本上是把它存储到我的'模板'对象。事情是这样的:

This gets messy. Fast. So, I looked into RequireJS's text plugin and that makes it much cleaner. Now, I have a bunch of HTML files, and I essentially store it into my 'templates' object. Something like this:

define(['text!/templates/template1.html',
    'text!/templates/template2.html',
    ...], 
    function(template1, template2, ...) {
        return {
            template1: template1,
            template2: template2,
            ....
        }
});

所以,现在的问题是HTTP请求。对于单独的模板,我有5个要求 - 1的template.js文件,然后4个独立的HTML模板文件。而且名单要保持增长。有一件事我想是把所有的HTML的一个文件,但似乎并没有去与AMD的方法。随着应用的发展,我可以这个只有加载HTML模板在必要的时候聪明很多 - 如果他们都是独立的。

So now the issue is HTTP requests. For templates alone, I have 5 requests - 1 for the template.js file, and then 4 separate HTML template files. And that list is going to keep growing. One thing I was thinking was to put all of the HTML in one file, but that doesn't seem to go with the AMD methodology. As the app progresses, I can be a lot smarter about this and only load HTML templates when necessary - if they're all separate.

有没有解决所有的HTML请求的方法吗?我想这是不是在生产环境中很好的做法。

Is there any way around all of the HTML requests? I assume this is not good practice in a production environment.

任何人有任何其他的想法如何完成我想要做什么?

Anyone have any other ideas for how to accomplish what I'm trying to do?

推荐答案

这是什么 RequireJS优化是。它结合了所有的模块到一个单一的文件作为pre-部署构建过程的一部分。按照 README文本插件

This is what the RequireJS Optimizer is for. It combines all of your modules into a single file as part of your pre-deploy build process. According to the README for the text plugin:

文本文件通过异步XMLHtt prequest(XHR)调用加载的,所以你只能从同一个域中的网页(见下文XHR限制)。

The text files are loaded via asynchronous XMLHttpRequest (XHR) calls, so you can only fetch files from the same domain as the web page (see XHR restrictions below).

不过,RequireJS优化器将内联任何文字!与实际的文本文件内容到模块中的引用,因此构建后,有文字模块!依赖性可以从其他领域使用。

However, the RequireJS optimizer will inline any text! references with the actual text file contents into the modules, so after a build, the modules that have text! dependencies can be used from other domains.

这篇关于使用模板RequireJS(text.js插件)和下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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