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

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

    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

    
    

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

    Install the Handlebars commandline script like so

    npm install -g handlebars
    

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

    handlebars events.tmpl -f events.tmpl.js
    

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

    
    

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

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

提交回复
热议问题