从单独的文件加载 underscore.js 模板

发布于 2024-12-28 22:00:01 字数 207 浏览 4 评论 0原文

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

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

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

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

望笑 2025-01-04 22:00:01

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

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

$.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,但如果您使用其他东西,原理是相同的。

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

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;
    }
});

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文