从单独的文件加载 underscore.js 模板 [英] Loading underscore.js templates from a separate file

查看:31
本文介绍了从单独的文件加载 underscore.js 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在项目中使用 underscore.js 进行模板化,模板存储在具有文本/模板类型的脚本标签中,并由 id 加载.我想知道是否可以继续使用相同的系统,但将模板移到单独的文件中?

I'm currently using underscore.js for templating in a project, templates are stored in script tags with a type of text/template and loaded by id. I'm wondering if it's possible to continue to use the same system, but move the templates to a separate file?

我能想到的唯一方法是在单独的文件中将模板声明为全局变量,但这看起来很难看.

The only way I can think about doing this is declaring the templates as global vars in a separate file, but that seems ugly.

注意:我不想在部署时使用 Jammit 或其他一些构建系统将所有内容混合到一个文件中,想知道是否有其他解决方案.

Note: I don't want to use Jammit or some other build system for mashing everything together into a single file at deployment time, wondering if there's another solution.

推荐答案

我个人使用 RequireJS 将我的模板加载到模块中,但如果您正在寻找其他东西,您可以使用 Ajax.

I personally use RequireJS to load my templates into a module but if you're looking for something else you can use Ajax.

只要您的模板位于同一个域中,您就可以通过 ajax 获取它们要求.如果使用我的小部件的人没有使用 AMD 兼容库,我将返回以下代码:

As long as your templates are located on the same domain you can get them through an ajax request. I fail back to the following code if whomever using my widget isn't using an AMD compatible library:

$.ajax({
    url: root.WIDGET.BaseUrl + 'templates/widget.html',
    asynx: false, // synchonous call in case code tries to use template before it's loaded
    success: function (response) {
        widgetTemplate = response;
    }
});

这假设您也在使用 jQuery,但如果您使用其他东西,原理是相同的.

This assumes you're using jQuery as well but the principle is the same if you're using something else.

这篇关于从单独的文件加载 underscore.js 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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