Node.js with Handlebars.js on server and client

前端 未结 7 2465
抹茶落季
抹茶落季 2020-12-02 08:21

I have an app in Node.js using Expressjs and Handlebars as the template engine.

Expressjs uses layouts and then renders views. The layout (layout.hbs) looks like th

7条回答
  •  不知归路
    2020-12-02 08:30

    I didn't like the precompilation solution (because I want to define templates in the same file where I will use them) nor the naive \{{ escape solution (because it needs the full Handlebars compiler and more javascript code) so I came up with an hybrid solution that uses Handlebars' helpers:

    1) Register a new helper called "template" on server configuration

    var hbs = require('hbs');
    hbs.registerHelper("template", function(key, options){
        var source = options.fn().replace("\\{{", "{{");
        var ret =
        '';
        return ret;
    });
    


    2) Use it anywhere in your client-side webpage (with \{{ escape for client-side parameters)

    {{#template "myTemplate"}}
        

    Hello \{{this.name}}!

    {{/template}}

    (the server will precompile it in something like this)

    
    


    3) Simply call the function where you need it in client-side javascript

    var generatedHtml = myTemplate("world");   // = 

    Hello world!

    $("#myDiv").html(generatedHtml); // or whatever

提交回复
热议问题