使用预编译模板与Handlebars.js (jQuery移动环境)



我在Handlebars中的模板预编译方面有些挣扎。我的jQuery移动项目是相当大的模板智慧,我希望预编译我使用的模板。

然而,我似乎找不到一个很好的解释(比如一步一步的教程)如何用把手来做这件事。

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

我猜做一些像

handlebars -s event.handlebars > event.compiled

并以某种方式包括事件编译的内容?但是,怎么称呼它呢?

我像这样调用我的模板

var source = $('#tmpl_profile').html(),
template = Handlebars.compile(source),
context = user.profile()),
html    = template(context);

希望有人能给我一些启示。

因此,经过多次尝试和错误(这是学习它的最佳方法),以下是适合我的方法。

首先,外部化你所有的模板,假设你有一个模板在脚本标签里面,比如
<script id="tmpl_ownevents" type="text/templates">
    {{#unless event}}
        <div class="notfoundevents"><p>No events for you</p></div>    
    {{/unless}}
</script>

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

像这样安装Handlebars命令行脚本

npm install -g handlebars

进入保存事件的文件夹。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);

现在你有了它,超级快速预编译的Handlebars模板。

另一个很好的选择是使用GruntJS。安装后:

npm install grunt-contrib- handles——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文件中。

用车把工作真是太棒了。

我是这样做的:

准备

我们假设所有的模板变量都在一个名为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
使用

在包含运行时之后,在HTML页面中包含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。它在编译模板时被自动剥离。

额外:如果你使用其中一个Jetbrains ide和Handlebars/Mustache插件,你甚至可以得到相当好的编辑器支持。

使用Grunt预编译车把模板

假设你已经安装了Node.js。如果你不喜欢,那就去做。

1)设置节点依赖:

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

{
  "devDependencies": {
   "grunt-contrib-handlebars": "~0.6.0",
    "grunt-contrib-watch": "~0.5.3",
    "handlebars": "~1.3.0"
  },
}

这个JSON文件告诉Node它需要安装哪些包。这有助于让其他开发人员快速启动并运行,正如您将在下一步中看到的那样。

2)安装节点依赖:

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

npm install grunt -g
npm install grunt-cli -g

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

npm install

现在您已经安装了所需的所有节点依赖项。在您的项目根目录中,您将看到一个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');
}

4)配置到你的喜好:

如果你不使用Require.js,你会想把handlebars.compile.options.amd改成false。您可能还想根据自己的喜好调整namespace选项。如果你使用的是require/amd模块,命名空间属性是不重要的(它的默认值是"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...

要单独运行编译任务,打开您的终端和cd到您的项目根目录,并运行命令:grunt handlebars:compile (grunt:handlebars也可以)。输出如下所示:

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

For Handlebars 2.0.0 alpha Update:

@Macro已经很清楚地解释了它是如何与一个模板一起工作的,请参阅如何使handlebars.js工作的答案

如果你在使用预编译模板时看到"TypeError: 'undefined' is not a function":

这个错误发生在"handlebar.runtime.js"第436行,当计算templateSpec时。调用容器、把手、上下文、选项。帮手,选项。Partials, options.data),

,因为安装的编译器与浏览器使用的编译器不匹配。最新的稳定版本是v1.3.0,如果你使用npm install handlebars,它会为你安装2.0.0-alpha4。

请使用

查看
handlebars any_your_template_before_compile.handlebars | grep "compiler"

这将给你喜欢,如果你确实安装了车把2.0.0-alpha4:

this.compiler = [5, '>=2.0.0']

第一个数字代表你的手柄编译器的版本。在浏览器控制台中输入以下代码,查看结果是否与版本匹配。

Handlebars.COMPILER_REVISION

如果你使用的是编译器5和浏览器版本4,那么你就会遇到上面的问题。

要修复它,使用以下命令安装handlebar 1.3.0

npm install handlebars@1.3.0 -g

然后试着再编译一次,你会看到,这一次,它会给你匹配的版本信息,你就可以使用预编译的模板了。

this.compilerInfo = [4, '>=1.0.0']


如果你有大量的模板,请解释:

首先外部化支撑模板的每个片段:event。车把,项目。车把等……你可以把它们放在一个文件夹里,比如"/templates"

编译所有文件,并使用以下命令将其连接成一个文件:

handlebars *.handlebars -f templates.js

包括handlebars.runtime,这个文件在你的HTML

<script src="/lib/handlebars.runtime.js"></script>
<script src="templates.js"></script>

模板将被注入到Handlebars中。模板的名称。例如,event。可以通过handlebars .tempaltes['event']访问车把

最新更新