Javascript 使用带有 Handlebars.js 的预编译模板(jQuery Mobile 环境)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8659787/
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
Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)
提问by Marco
I am struggling somewhat with pre-compilation of templates in Handlebars. My jQuery Mobile project is getting pretty big template-wise and I wish to pre-compile the templates I use.
我在 Handlebars 中对模板的预编译有些挣扎。我的 jQuery Mobile 项目在模板方面变得越来越大,我希望预编译我使用的模板。
However I can't seem to find a good explanation (like a step by step tutorial) of how to do this with Handlebars.
但是,我似乎无法找到有关如何使用 Handlebars 执行此操作的好的解释(例如分步教程)。
I still have my templates all inline using the script tags. I have handlebars installed using NPM. But now I am kinda lost in how to proceed.
我仍然使用脚本标签将我的模板全部内联。我使用 NPM 安装了车把。但现在我有点迷失在如何继续。
I am guessing doing something like
我猜想做类似的事情
handlebars -s event.handlebars > event.compiled
and somehow including the event.compiled contents? But then, how to call it.
并以某种方式包括 event.compiled 内容?但是,如何调用它。
I am calling my templates like so
我这样称呼我的模板
var source = $('#tmpl_profile').html(),
template = Handlebars.compile(source),
context = user.profile()),
html = template(context);
Hope someone can shed some light on this for me.
希望有人可以为我阐明这一点。
回答by Marco
So after much trial and error (which is the best way to learn it) here's the way that works for me.
因此,经过多次反复试验(这是学习它的最佳方法),这就是对我有用的方法。
First- externalize all your templates, say you have a template inside script tags like
首先-外部化您的所有模板,假设您在脚本标签内有一个模板,例如
<script id="tmpl_ownevents" type="text/templates">
{{#unless event}}
<div class="notfoundevents"><p>No events for you</p></div>
{{/unless}}
</script>
Create a new file called events.tmpl and copy/paste the template into that. Be sure to remove the script elements themselves, this gotcha bit me in the a..
创建一个名为 events.tmpl 的新文件并将模板复制/粘贴到其中。一定要删除脚本元素本身,这个问题在 a..
Install the Handlebars commandline script like so
像这样安装 Handlebars 命令行脚本
npm install -g handlebars
go to the folder you have saved events.tmpl into and run
转到您保存 events.tmpl 的文件夹并运行
handlebars events.tmpl -f events.tmpl.js
Include the compiled javascript into your HTML after you included Handlebars.js
包含 Handlebars.js 后,将编译后的 javascript 包含到 HTML 中
<script src="events.tmpl.js"></script>
Now all that is left is change your normal template code into something resembling the following
现在剩下的就是将您的正常模板代码更改为类似于以下内容
var template = Handlebars.templates['events.tmpl'], // your template minus the .js
context = events.all(), // your data
html = template(context);
And there you have it, super fast pre-compiled Handlebars templates.
有了它,超快速的预编译 Handlebars 模板。
回答by Scott Silvi
Another great option for this is to use GruntJS. Once installed:
另一个很好的选择是使用GruntJS。安装后:
npm install grunt-contrib-handlebars --save-dev
npm install grunt-contrib-handlebars --save-dev
Then inside your gruntfile.js
然后在你的 gruntfile.js 里面
grunt.initConfig({
dirs: {
handlebars: 'app/handlebars'
},
watch: {
handlebars: {
files: ['<%= handlebars.compile.src %>'],
tasks: ['handlebars:compile']
}
},
handlebars: {
compile: {
src: '<%= dirs.handlebars %>/*.handlebars',
dest: '<%= dirs.handlebars %>/handlebars-templates.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-handlebars');
Then you simply type grunt watch
from your console, and grunt will automatically compile all *.handlebars files into your handlebars-templates.js file.
然后你只需grunt watch
从控制台输入,grunt 就会自动将所有 *.handlebars 文件编译到你的 handlebars-templates.js 文件中。
Really rad way to work with handlebars.
与车把一起工作的真正方式。
回答by apfelbox
Here is the way I do it:
这是我的做法:
Preparation
准备
We will just assume all your template variables are in a variable called context
:
我们将假设您所有的模板变量都在一个名为 的变量中context
:
var context = {
name: "Test Person",
...
};
Where to put your templates
将模板放在哪里
Create a directory containing all your templates (we'll call it templates/
)
Add your templates here, called filename.handlebars
.
创建一个包含所有模板的目录(我们称之为templates/
) 在此处添加您的模板,称为filename.handlebars
.
Your directory structure:
您的目录结构:
.
└── templates
├── another_template.handlebars
└── my_template.handelbars
Compiling your templates
编译你的模板
First go to your root directory, then compile your templates with the npm CLI program:
首先转到您的根目录,然后使用 npm CLI 程序编译您的模板:
handlebars templates/*.handlebars -f compiled.js
handlebars templates/*.handlebars -f compiled.js
New directory structure:
新目录结构:
.
├── compiled.js
└── templates
├── another_template.handlebars
└── my_template.handlebars
Usage
用法
Include the compiled.js
in your HTML page after you include the runtime:
包含compiled.js
运行时后,将包含在您的 HTML 页面中:
<script src="handlebars.runtime.js"></script>
<script src="compiled.js"></script>
Render your templates using the global Handlebars
object:
使用全局Handlebars
对象渲染您的模板:
// If you used JavaScript object property conform file names
// Original filename: "my_template.handlebars"
Handlebars.templates.my_template(context)
// if you used special characters which are not allowed in JavaScript properties
// Original filename: "my-template.handlebars"
Handlebars.templates["my-template"](context)
Remarks
评论
Note the file extension .handlebars
. It is automatically stripped when compiling the templates.
注意文件扩展名.handlebars
。编译模板时它会自动剥离。
Extra: if you use one of the Jetbrains IDEs together with the Handlebars/Mustache pluginyou even get quite a good editor support.
额外:如果您将 Jetbrains IDE 之一与Handlebars/Mustache 插件一起使用,您甚至可以获得相当好的编辑器支持。
回答by Cory Danielson
Precompiling Handlebars Templates with Grunt
使用 Grunt 预编译 Handlebars 模板
Assuming you have Node.js installed. If you don't, go do that.
假设您安装了 Node.js。如果你不这样做,那就去做吧。
1) Setting up Node dependencies:
1) 设置节点依赖:
In your applications root directory add a file named package.json
. Paste the following into that file:
在您的应用程序根目录中添加一个名为package.json
. 将以下内容粘贴到该文件中:
{
"devDependencies": {
"grunt-contrib-handlebars": "~0.6.0",
"grunt-contrib-watch": "~0.5.3",
"handlebars": "~1.3.0"
},
}
This JSON file tells Node what packages it needs to install. This helps to get other developers get up-and-running very quickly, as you'll see in the next step.
这个 JSON 文件告诉 Node 它需要安装哪些包。这有助于让其他开发人员快速启动并运行,您将在下一步中看到。
2) Installing Node Dependencies:
2) 安装节点依赖:
In your terminal/command prompt/powershell, cd
into your projects root directory and run the following commands:
在您的终端/命令提示符/powershell 中,cd
进入您的项目根目录并运行以下命令:
npm install grunt -g
npm install grunt-cli -g
And to install the dependencies listed in your package.json:
并安装 package.json 中列出的依赖项:
npm install
Now you've installed all of the node dependencies that you need. In your projects root directory, you'll see a node_modules folder
.
现在您已经安装了所需的所有节点依赖项。在您的项目根目录中,您将看到一个node_modules folder
.
3) Configuring Grunt:
3)配置咕噜声:
In your projects root directory, create a file named Gruntfile.js
. Paste the following into that file:
在您的项目根目录中,创建一个名为Gruntfile.js
. 将以下内容粘贴到该文件中:
module.exports = function(grunt) {
var TEMPLATES_LOCATION = "./src/templates/", // don't forget the trailing /
TEMPLATES_EXTENSION = ".hbs",
TEMPLATES_OUTPUT_LOCATION = TEMPLATES_LOCATION, // don't forget the trailing /
TEMPLATES_OUTPUT_FILENAME = "compiled_templates.js"; // don't forget the .js
grunt.initConfig({
watch: {
handlebars: {
files: [TEMPLATES_LOCATION + '**/*' + TEMPLATES_EXTENSION],
tasks: ['handlebars:compile']
}
},
handlebars: {
compile: {
src: TEMPLATES_LOCATION + '**/*' + TEMPLATES_EXTENSION,
dest: TEMPLATES_OUTPUT_LOCATION + TEMPLATES_OUTPUT_FILENAME,
options: {
amd: true,
namespace: "templates"
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-handlebars');
grunt.loadNpmTasks('grunt-contrib-watch');
}
4) Configuring to Your Liking:
4) 根据您的喜好进行配置:
If you are not using Require.js, you'll want to change handlebars.compile.options.amd
to false
. You may also want to tweak the namespace
option to your liking. If you're using require/amd modules, the namespace property is unimportant (it's default is "JST", if you remove it).
如果您不使用 Require.js,则需要更改handlebars.compile.options.amd
为false
. 您可能还想namespace
根据自己的喜好调整选项。如果您使用的是 require/amd 模块,则命名空间属性并不重要(如果您将其删除,则它的默认值为“JST”)。
Because all project structures are a little bit different, you'll need to configure the Gruntfile just a little bit. Modify the constants TEMPLATES_LOCATION
, TEMPLATES_EXTENSION
, TEMPLATES_OUTPUT_LOCATION
, TEMPLATES_OUTPUT_FILENAME
to fit your project.
由于所有项目结构都略有不同,因此您只需要稍微配置 Gruntfile。修改常量TEMPLATES_LOCATION
, TEMPLATES_EXTENSION
, TEMPLATES_OUTPUT_LOCATION
,TEMPLATES_OUTPUT_FILENAME
以适合您的项目。
If your templates are scattered throughout your application, you'll want to change TEMPLATES_LOCATION
to the lowest directory possible. Make sure your templates are isolated from your node_modules, bower_components or any other 3rd party directories, because you don't want Grunt to compile 3rd Party templates into your applications compiled templates. If you include all of your own code in a ./src
, ./js
, ./app
directory, you'll be okay.
如果您的模板分散在整个应用程序中,您将需要更改TEMPLATES_LOCATION
到尽可能低的目录。确保您的模板与 node_modules、bower_components 或任何其他 3rd 方目录隔离,因为您不希望 Grunt 将 3rd 方模板编译到您的应用程序编译模板中。如果您将自己的所有代码都包含在./src
, ./js
,./app
目录中,那就没问题了。
5) Compiling templates with Grunt:
5) 用 Grunt 编译模板:
To run grunt in the background, open your terminal and cd
into your projects root directory and run the command: grunt watch:handlebars
(just grunt watch
works as well). With grunt running in the background, all changes to your template files will be automatically compiled and the output file specified handlebars.compile.dest
will be rewritten as needed. The output will look something like this:
要在后台运行的呼噜声,打开你的终端,并cd
为您的项目的根目录,然后运行命令:grunt watch:handlebars
(只grunt watch
适用为好)。随着 grunt 在后台运行,对模板文件的所有更改都将被自动编译,并handlebars.compile.dest
根据需要重写指定的输出文件。输出将如下所示:
Running "watch" task
Waiting...
To run the compile task alone, open your terminal and cd
into your projects root directory and run the command: grunt handlebars:compile
(just grunt:handlebars
works as well). The output will look something like:
单独运行的编译任务,打开你的终端,并cd
为您的项目的根目录,然后运行命令:grunt handlebars:compile
(只grunt:handlebars
适用为好)。输出将类似于:
Running "handlebars:compile" <handlebars> task
File "./src/templates/compiled_templates.js" created.
Done, without errors.
回答by yeelan
For Handlebars 2.0.0 alpha Update:
对于 Handlebars 2.0.0 alpha 更新:
@Macro has explained quite clearly how it works with 1 piece of template, please see this answer for how to make handlebars.js works
@Macro 已经非常清楚地解释了它如何与 1 个模板一起工作,请参阅此答案以了解如何使 handlebars.js 工作
If you see "TypeError: 'undefined' is not a function" when using precompiled templates:
如果在使用预编译模板时看到“TypeError: 'undefined' is not a function”:
This error happened at "handlebar.runtime.js" line 436 when evaluting templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data),
在评估 templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data) 时,此错误发生在“handlebar.runtime.js”第 436 行,
because the compiler npm installed is not matching the one used by the browser. The latest stable version downloaded is v1.3.0 while if you use npm install handlebars, it will install 2.0.0-alpha4 for you.
因为安装的编译器 npm 与浏览器使用的编译器不匹配。下载的最新稳定版本是 v1.3.0,而如果您使用 npm install handlebars,它将为您安装 2.0.0-alpha4。
Please check it out using
请使用
handlebars any_your_template_before_compile.handlebars | grep "compiler"
which will give you like, if you indeed installed handlebar 2.0.0-alpha4:
如果您确实安装了把手 2.0.0-alpha4,这会给您喜欢的:
this.compiler = [5, '>=2.0.0']
With the first number stands for the version for your handlebar compiler. Type in the following code in browser console, see if the result match the version.
第一个数字代表您的把手编译器的版本。在浏览器控制台中输入以下代码,查看结果是否与版本匹配。
Handlebars.COMPILER_REVISION
If you have compiler 5 with browser revison 4, then you will have the above problem.
如果您的浏览器版本为 4 的编译器 5,那么您将遇到上述问题。
To fix it, install handlebar 1.3.0 with the following command
要修复它,请使用以下命令安装车把 1.3.0
npm install [email protected] -g
Then try to compile it again, you will see this time, it gives you matching version info and you are good to go with the precompiled templates.
然后再次尝试编译它,这一次您会看到,它为您提供匹配的版本信息,您可以使用预编译模板。
this.compilerInfo = [4, '>=1.0.0']
Just explain if you have tons of templates:
如果您有大量模板,请解释一下:
Firstly externalize each piece of your braced templates: event.handlebars, item.handlebars, etc... You can put them all in one folder, say "/templates"
首先外部化你的支撑模板的每一部分:event.handlebars、item.handlebars 等......你可以把它们都放在一个文件夹中,比如“/templates”
Compile all the files and concatenate it into 1 file with the following command:
使用以下命令编译所有文件并将其连接为 1 个文件:
handlebars *.handlebars -f templates.js
And include handlebars.runtime, this file in your HTML
并在 HTML 中包含 handlebars.runtime,这个文件
<script src="/lib/handlebars.runtime.js"></script>
<script src="templates.js"></script>
The templates will be injected into Handlebars.templates by their name. For example, event.handlebars can be accessed by Handlebars.tempaltes['event'].
模板将按名称注入 Handlebars.templates。例如,可以通过 Handlebars.tempaltes['event'] 访问 event.handlebars。