Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)

前端 未结 5 958
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 16:30

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 template

5条回答
  •  遥遥无期
    2020-11-30 17:06

    Here is the way I do it:

    Preparation

    We will just assume all your template variables are in a variable called 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.

    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:

    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:

    
    
    

    Render your templates using the global Handlebars object:

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

    Extra: if you use one of the Jetbrains IDEs together with the Handlebars/Mustache plugin you even get quite a good editor support.

提交回复
热议问题