使用带有 Handlebars.js 的预编译模板(jQuery Mobile 环境) [英] Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)

查看:17
本文介绍了使用带有 Handlebars.js 的预编译模板(jQuery Mobile 环境)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Handlebars 中预编译模板时遇到了一些困难.我的 jQuery Mobile 项目在模板方面变得越来越大,我希望预编译我使用的模板.

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 执行此操作的好的解释(例如分步教程).

However I can't seem to find a good explanation (like a step by step tutorial) of how to do this with Handlebars.

我仍然使用脚本标签内联所有模板.我使用 NPM 安装了车把.但现在我有点迷失在如何继续.

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.

我猜想做类似的事情

handlebars -s event.handlebars > event.compiled

并以某种方式包括 event.compiled 内容?但是,如何调用它.

and somehow including the event.compiled contents? But then, how to call it.

我这样称呼我的模板

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.

推荐答案

经过多次反复试验(这是学习它的最佳方式)后,这里有适合我的方法.

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>

创建一个名为 events.tmpl 的新文件并将模板复制/粘贴到其中.一定要删除脚本元素本身,这个问题让我陷入了困境

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..

像这样安装 Handlebars 命令行脚本

Install the Handlebars commandline script like so

npm install -g handlebars

转到您保存 events.tmpl 的文件夹并运行

go to the folder you have saved events.tmpl into and run

handlebars events.tmpl -f events.tmpl.js

在包含 Handlebars.js 后将编译的 javascript 包含到 HTML 中

Include the compiled javascript into your HTML after you included Handlebars.js

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

这就是超快速的预编译 Handlebars 模板.

And there you have it, super fast pre-compiled Handlebars templates.

这篇关于使用带有 Handlebars.js 的预编译模板(jQuery Mobile 环境)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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