使用Handlebars.js预先编译的模板(jQuery Mobile环境)

Mar*_*rco 67 javascript jquery-mobile handlebars.js

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

但是,我似乎无法找到一个很好的解释(如一步一步的教程)如何使用Handlebars做到这一点.

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

我猜是在做类似的事情

handlebars -s event.handlebars > event.compiled
Run Code Online (Sandbox Code Playgroud)

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

我正在调用我的模板

var source = $('#tmpl_profile').html(),
template = Handlebars.compile(source),
context = user.profile()),
html    = template(context);
Run Code Online (Sandbox Code Playgroud)

希望有人可以为我阐明这一点.

Mar*_*rco 115

经过多次试验和错误(这是学习它的最佳方式)之后,这就是适合我的方式.

首先外部化所有模板,比如你在脚本标签里面有一个模板

<script id="tmpl_ownevents" type="text/templates">
    {{#unless event}}
        <div class="notfoundevents"><p>No events for you</p></div>    
    {{/unless}}
</script>
Run Code Online (Sandbox Code Playgroud)

创建一个名为events.tmpl的新文件,并将模板复制/粘贴到该文件中.一定要删除脚本元素本身,这有点让我在...

像这样安装Handlebars命令行脚本

npm install -g handlebars
Run Code Online (Sandbox Code Playgroud)

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

handlebars events.tmpl -f events.tmpl.js
Run Code Online (Sandbox Code Playgroud)

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

<script src="events.tmpl.js"></script>
Run Code Online (Sandbox Code Playgroud)

现在剩下的就是将您的普通模板代码更改为类似以下的内容

var template = Handlebars.templates['events.tmpl'], // your template minus the .js
    context = events.all(), // your data
    html    = template(context);
Run Code Online (Sandbox Code Playgroud)

而且你有它,超快速的预编译Handlebars模板.

  • 在语义上,我发现最好不要给模板文件"js"扩展名,因为这些文件不是"纯粹的"javascript文件.把手编译器理解"把手"扩展并将其从最终模板名称中删除,因此对于events.handlebars而不是Handlebars.templates ['events.tmpl']; 你得到Handlebars.templates ['events']; 我发现有点清洁. (28认同)
  • 对于那些使用RequireJS的人,在handlebars命令行实用程序中有一个选项(`-a`或`--amd`),它告诉它创建一个AMD样式函数,稍后可以使用RequireJS加载它. (7认同)
  • 您是否必须拥有多个模板的多个文件?有人可以解释你如何外化10+模板?理想情况下,它们都在一个文件中,通过删除脚本标记,您删除了特定模板可能具有的唯一标识. (5认同)
  • @ xckpd7你不需要外化模板,参见[小提琴](http://jsfiddle.net/aKwhJ/1/); 所以你可以编译任何数量的把手并将它们连接到单个文件,编译时间名称将决定_Handlebars.templates_属性 (3认同)

Sco*_*lvi 15

另一个很好的选择是使用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');
Run Code Online (Sandbox Code Playgroud)

然后你只需grunt watch从你的控制台输入,然后grunt会自动将所有*.handlebars文件编译到你的handlebars-templates.js文件中.

真正的拉杆方式与车把一起工作.


apf*_*box 10

这是我的方式:

制备

我们将假设所有模板变量都在一个名为的变量中context:

var context = {
    name: "Test Person",
    ...
};
Run Code Online (Sandbox Code Playgroud)

放置模板的位置

创建一个包含所有模板的目录(我们称之为templates/)在这里添加模板,调用filename.handlebars.

你的目录结构:

.
??? templates
    ??? another_template.handlebars
    ??? my_template.handelbars
Run Code Online (Sandbox Code Playgroud)

编译模板

首先转到根目录,然后使用npm CLI程序编译模板:

handlebars templates/*.handlebars -f compiled.js

新目录结构:

.
??? compiled.js
??? templates
    ??? another_template.handlebars
    ??? my_template.handlebars
Run Code Online (Sandbox Code Playgroud)

用法

包含compiled.js运行时后,在HTML页面中包含:

<script src="handlebars.runtime.js"></script>
<script src="compiled.js"></script>
Run Code Online (Sandbox Code Playgroud)

使用全局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)
Run Code Online (Sandbox Code Playgroud)

备注

请注意文件扩展名.handlebars.编译模板时会自动剥离它.

额外:如果您使用其中一个Jetbrains IDE和Handlebars/Moustache插件,您甚至可以获得相当好的编辑器支持.


Cor*_*son 6

使用Grunt预编译Handlebars模板

假设你安装了Node.js. 如果你不这样做,那就去做吧.

1)设置节点依赖性:

在应用程序根目录中添加一个名为的文件package.json.将以下内容粘贴到该文件中:

{
  "devDependencies": {
   "grunt-contrib-handlebars": "~0.6.0",
    "grunt-contrib-watch": "~0.5.3",
    "handlebars": "~1.3.0"
  },
}
Run Code Online (Sandbox Code Playgroud)

此JSON文件告诉Node需要安装哪些软件包.这有助于让其他开发人员快速启动并运行,您将在下一步中看到.

2)安装节点依赖项:

在您的终端/命令提示符/ powershell中,cd进入项目根目录并运行以下命令:

npm install grunt -g
npm install grunt-cli -g
Run Code Online (Sandbox Code Playgroud)

并安装package.json中列出的依赖项:

npm install
Run Code Online (Sandbox Code Playgroud)

现在您已经安装了所需的所有节点依赖项.在您的项目根目录中,您将看到一个node_modules folder.

3)配置Grunt:

在项目根目录中,创建一个名为的文件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');

}
Run Code Online (Sandbox Code Playgroud)

4)配置你的喜好:

如果您没有使用Require.js,则需要更改handlebars.compile.options.amdfalse.您可能还想namespace根据自己的喜好调整选项.如果您正在使用require/amd模块,则namespace属性并不重要(如果删除它,则默认为"JST").

因为所有项目结构都有点不同,所以您需要稍微配置Gruntfile.修改常量TEMPLATES_LOCATION,TEMPLATES_EXTENSION,TEMPLATES_OUTPUT_LOCATION,TEMPLATES_OUTPUT_FILENAME以满足您的项目.

如果您的模板分散在整个应用程序中,您将需要更改TEMPLATES_LOCATION为可能的最低目录.确保您的模板与node_modules,bower_components或任何其他第三方目录隔离,因为您不希望Grunt将第三方模板编译到您的应用程序编译模板中.如果包括所有的在自己的代码./src,./js,./app目录,你会好起来的.

5)使用Grunt编译模板:

要在后台运行grunt,打开终端并cd进入项目根目录并运行命令:(也grunt watch:handlebars可以grunt watch正常工作).随着grunt在后台运行,模板文件的所有更改都将自动编译,指定的输出文件handlebars.compile.dest将根据需要进行重写.输出看起来像这样:

Running "watch" task
Waiting...
Run Code Online (Sandbox Code Playgroud)

要单独运行编译任务,请打开终端并cd进入项目根目录并运行命令:(也grunt handlebars:compile可以grunt:handlebars正常工作).输出看起来像:

Running "handlebars:compile" <handlebars> task
File "./src/templates/compiled_templates.js" created.

Done, without errors.
Run Code Online (Sandbox Code Playgroud)