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

前端 未结 5 960
被撕碎了的回忆
被撕碎了的回忆 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:05

    For Handlebars 2.0.0 alpha Update:

    @Macro has explained quite clearly how it works with 1 piece of template, please see this answer for how to make handlebars.js works

    If you see "TypeError: 'undefined' is not a function" when using precompiled templates:

    This error happened at "handlebar.runtime.js" line 436 when evaluting templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data),

    because the compiler npm installed is not matching the one used by the browser. The latest stable version downloaded is v1.3.0 while if you use npm install handlebars, it will install 2.0.0-alpha4 for you.

    Please check it out using

    handlebars any_your_template_before_compile.handlebars | grep "compiler"
    

    which will give you like, if you indeed installed handlebar 2.0.0-alpha4:

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

    With the first number stands for the version for your handlebar compiler. Type in the following code in browser console, see if the result match the version.

    Handlebars.COMPILER_REVISION
    

    If you have compiler 5 with browser revison 4, then you will have the above problem.

    To fix it, install handlebar 1.3.0 with the following command

    npm install handlebars@1.3.0 -g
    

    Then try to compile it again, you will see this time, it gives you matching version info and you are good to go with the precompiled templates.

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


    Just explain if you have tons of templates:

    Firstly externalize each piece of your braced templates: event.handlebars, item.handlebars, etc... You can put them all in one folder, say "/templates"

    Compile all the files and concatenate it into 1 file with the following command:

    handlebars *.handlebars -f templates.js
    

    And include handlebars.runtime, this file in your HTML

    
    
    

    The templates will be injected into Handlebars.templates by their name. For example, event.handlebars can be accessed by Handlebars.tempaltes['event'].

提交回复
热议问题