Can Mustache Templates do template extension?

后端 未结 9 527
醉话见心
醉话见心 2021-01-30 06:39

I\'m new to Mustache.

Many templating languages (e.g., Django / Jinja) will let you extend a \"parent\" template like so...

ba

9条回答
  •  无人共我
    2021-01-30 07:02

    I recently found myself in the same boat, except I came from a mako background.

    Mustache does not allow for template extension/inheritance but there are a few options available to you that I know of.

    1. You could use partials:

      {{>header}}
          Hello {{name}}
      {{>footer}}
      
    2. You could inject template pre-processing functions into the context for each template that needs to inherit from some other page:

      {{#extendBase}}      
          Hello {{name}}
      {{/extendBase}} 
      

      Hash:

      {
         "name": "Walden",
         "extendBase": function() {
             return function(text) {
                 return "" + render(text) + ""
             }
         }
      }
      
    3. Prepend and append the desired HTML to the relevant pages in your controller.

    4. Have a layout template ala:

      {{>header}}
          {{{body}}}
      {{>footer}}
      

      And render the body in your controller, passing that to the layout template as a variable named body.

    5. Implement template inheritance, pre-mustache, in your code that loads templates.

    I wouldn't, however, use the triple mustache because I don't want unescaped HTML to be appearing anywhere, it's just too risky in my opinion.

    If someone else has a better solution to this problem I'd love to hear it as well, since I haven't yet taken the plunge in any one of these directions.

提交回复
热议问题