javascript 如何将我的 Mustache / Handlebars 模板存放在单独的文件中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7795469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stock my Mustache / Handlebars templates in separate files?
提问by mdcarter
I'm using handlebars.js on a project and I'm starting to have a fair amount of templates. For now they are stored in my main template app file, like this :
我在一个项目中使用 handlebars.js 并且我开始拥有相当数量的模板。现在它们存储在我的主模板应用程序文件中,如下所示:
<script id="avatar_tpl" type="text/html">
bla bla bla {{var}} bla bla bla
</script>
I'm wondering if there is a way to put them in a separate file like a .js file or something, to avoid stacking them up in my source code page.
我想知道是否有办法将它们放在一个单独的文件中,例如 .js 文件或其他文件,以避免将它们堆叠在我的源代码页中。
I'm aware that there are several solutions to call theses templates via Ajax, but that seems to result in too much unnecessary requests for me.
我知道有几种解决方案可以通过 Ajax 调用这些模板,但这似乎给我带来了太多不必要的请求。
Thank you
谢谢
采纳答案by Mauvis Ledford
I created and open-sourced NodeIntervalfor this exact same problem of too many js templates in my HTML page.
我为 HTML 页面中太多 js 模板的完全相同的问题创建并开源了NodeInterval。
It allows you to put all your templates into a templates folder organized in whatever hierarchy you like. It has a built in watch
capability so that as you modify any of these templates it automatically updates your HTML page. I use it alongside SASSfor my CSS.
它允许您将所有模板放入以您喜欢的任何层次结构组织的模板文件夹中。它具有内置watch
功能,因此当您修改任何这些模板时,它会自动更新您的 HTML 页面。我将它与SASS一起用于我的 CSS。
I use it daily with underscore templates but it should work fine with moustache templates as well:
我每天都将它与下划线模板一起使用,但它也可以与 mustache 模板一起使用:
回答by swatkins
Couldn't you just include a js file with your templates as js variables? Not tested, just thinking here:
你不能只在你的模板中包含一个 js 文件作为 js 变量吗?没有测试,只是想在这里:
//in your html page
<script id="avatar_tpl" type="text/html" src="mytemplates.js"></script>
// then in your mytemplates.js file
var template_1 = "{{ content }}";
var template_2 = "{{ content }}";
// and you could use it like this back in html page
var template1 = Handlebars.compile(template_1);
var template2 = Handlebars.compile(template_2);
回答by Miao Siyu
if you are using jquery, you could create an invisible div with id "template-holder"
如果你使用 jquery,你可以创建一个不可见的 div,id 为“template-holder”
then use :
然后使用:
$("#template-holder").load([url here])
to load the html into the div then use :
将 html 加载到 div 中,然后使用:
var templatestr = $("#template-holder").find("#avatar_tpl").html()
to get the template
获取模板
:)
:)
回答by uadrive
I created a Lazy Load javascript file that loads the templates only as needed. It's performing the AJAX calls, but seems to work quite well.
我创建了一个 Lazy Load javascript 文件,只在需要时加载模板。它正在执行 AJAX 调用,但似乎工作得很好。
var Leuly = Leuly || {};
Leuly.TemplateManager = (function ($) {
var my = {};
my.Templates = {};
my.BaseUrl = "/Templates/";
my.Initialize = function (options) {
/// <summary>
/// Initializes any settings needed for the template manager to start.
/// </summary>
/// <param name="options">sets any optional parameters needed</param>
if (options && options.BaseUrl) {
my.BaseUrl = options.BaseUrl;
}
};
my.GetTemplate = function (templateName, success, baseUrl) {
/// <summary>
/// makes a request to retrieve a particular template
/// </summary>
/// <param name="templateName">name of the template to retrieve</param>
/// <param name="success">event returning the success</param>
var template = my.Templates[templateName];
if (template == null) {
template = my.LoadTemplate(templateName, success, baseUrl);
}
else {
success(template, true);
}
};
my.LoadTemplate = function (templateName, success, baseUrl) {
/// <summary>
/// makes a request to load the template from the template source
/// </summary>
/// <param name="templateName">name of the template to retrieve</param>
/// <param name="success">event returning the success</param>
var root = baseUrl == null ? my.BaseUrl : baseUrl;
$.get(root + templateName, function (result) {
my.Templates[templateName] = result;
if (result != null && success != null) {
success(result, true);
}
});
};
return my;
} (jQuery));
$(function () {
Leuly.TemplateManager.Initialize();
});
回答by morgancodes
I've been rolling all my scripts and templates in to one big .js file for several projects now. I use a java-based build tool, ant, to concatenate and manage various processing scripts for my js.
我现在已经将我的所有脚本和模板整合到一个大的 .js 文件中,用于多个项目。我使用基于 Java 的构建工具 ant 来连接和管理我的 js 的各种处理脚本。
The biggest problem with storing large templates in javascript variables is javascript's lack of multi-line strings. I deal with this by writing my files with a python-like triple-quote syntax:
在 javascript 变量中存储大型模板的最大问题是 javascript 缺少多行字符串。我通过使用类似 python 的三引号语法编写我的文件来处理这个问题:
var templateVariable = '''
<div>
<div></div>
</div>
'''
I then run this custom-syntax javascript file though the python script included below, which turns it in to legal javascript:
然后我通过下面包含的 python 脚本运行这个自定义语法 javascript 文件,它将它转换为合法的 javascript:
#!/usr/bin/env python
# encoding: utf-8
"""
untitled.py
Created by Morgan Packard on 2009-08-24.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
import sys
import os
def main():
f = open(sys.argv[1], 'r')
contents = f.read()
f.close
split = contents.split("'''")
print "split length: " + str(len(split))
processed = ""
for i in range(0, len(split)):
chunk = split[i]
if i % 2 == 1:
processedChunk = ""
for i,line in enumerate(chunk.split("\n")):
if i != 0:
processedChunk = processedChunk + "+ "
processedChunk = processedChunk + "\"" + line.strip().replace("\"", "\\"").replace('\'', '\\'') + "\"" + "\n"
chunk = processedChunk
processed = processed + chunk
f = open(sys.argv[1], 'w')
f.write(processed)
f.close()
if __name__ == '__main__':
main()
Working this way, I can code templates in more-or-less pure html, and deploy them, along with application code, inside a single .js file.
通过这种方式,我可以在或多或少的纯 html 中编写模板,并将它们与应用程序代码一起部署在单个 .js 文件中。
回答by Francisco Valdez
I'm not familiar with handlebars.js but, have you tried this?:
我不熟悉 handlebars.js 但是,你试过这个吗?:
<script id="avatar_tpl" type="text/html" src="myscript.html"></script>