我在处理Handlebar中的模板预编译时遇到了一些困难。我的jQuery移动项目在模板方面变得相当大,我希望预编译我使用的模板。
然而,我似乎找不到一个很好的解释(比如一步一步的教程)来解释如何使用Handlebar来做到这一点。
我仍然有我的模板,所有内联使用脚本标签。我使用NPM安装了车把。但现在我有点迷失在如何继续下去的问题上。
我猜是做一些像这样的事情
handlebars -s event.handlebars > event.compiled
并以某种方式包含event.compiled内容?但是,如何调用它呢?
我这样命名我的模板
var source = $('#tmpl_profile').html(),
template = Handlebars.compile(source),
context = user.profile()),
html = template(context);
希望有人能为我提供一些线索。
发布于 2011-12-29 17:45:56
因此,在经历了多次尝试和错误之后(这是学习它的最好方法),下面是对我有效的方法。
首先-外部化所有的模板,假设在脚本标记中有一个模板,比如
<script id="tmpl_ownevents" type="text/templates">
{{#unless event}}
<div class="notfoundevents"><p>No events for you</p></div>
{{/unless}}
</script>
创建一个名为events.tmpl的新文件,并将模板复制/粘贴到其中。一定要删除脚本元素本身,这让我在a..
像这样安装Handlebar命令行脚本
npm install -g handlebars
转到已保存events.tmpl的文件夹,然后运行
handlebars events.tmpl -f events.tmpl.js
在包含Handlebars.js之后,将编译后的javascript包含到HTML中
<script src="events.tmpl.js"></script>
现在剩下的就是将正常的模板代码更改为类似于以下内容的代码
var template = Handlebars.templates['events.tmpl'], // your template minus the .js
context = events.all(), // your data
html = template(context);
现在你有了它,超级快速的预编译的Handlebar模板。
发布于 2013-11-30 04:40:56
另一个很好的选择是使用GruntJS。安装后:
npm install grunt-contrib-handlebars -save-dev
然后进入你的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');
然后,您只需在控制台中输入grunt watch
,grunt将自动将所有*.handlebars文件编译到您的handlebars templates.js文件中。
使用车把的方式真的很棒。
发布于 2014-02-20 01:45:23
下面是我这样做的方法:
准备工作
我们假设所有的模板变量都在一个名为context
的变量中
var context = {
name: "Test Person",
...
};
将模板放在哪里
创建一个包含所有模板的目录(我们将其称为templates/
),在此处添加名为filename.handlebars
的模板。
您的目录结构:
.
└── templates
├── another_template.handlebars
└── my_template.handelbars
编译你的模板
首先转到根目录,然后使用npm CLI程序编译模板:
handlebars templates/*.handlebars -f compiled.js
新的目录结构:
.
├── compiled.js
└── templates
├── another_template.handlebars
└── my_template.handlebars
用法
在包含运行时之后,在您的超文本标记语言页面中包含compiled.js
:
<script src="handlebars.runtime.js"></script>
<script src="compiled.js"></script>
使用全局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)
备注
请注意文件扩展名.handlebars
。它会在编译模板时自动剥离。
Extra:如果您将Jetbrains IDE之一与Handlebars/Mustache plugin一起使用,您甚至可以获得相当好的编辑器支持。
https://stackoverflow.com/questions/8659787
复制相似问题