Escape double braces {{ … }} in Mustache template. (templating a template in NodeJS)

别来无恙 提交于 2019-11-26 22:45:24

问题


I'm trying to template a template, like below:

{{{
{
  "name" : "{{name}}",
  "description" : "{{description}}"
}
}}}

{{{debug this}}}

<h1>{{name}}</h1>

Where I want to triple brackets to stay, but double brackets to be replaced with the JSON passed in. Anyone know the best way to do this without writing post-process JS code, and if not, is there a good nodeJS template engine for this type of scenario?


回答1:


You can switch delimiters to something that won't conflict with the triple mustaches, like erb-style tags:

{{=<% %>=}}
{{{
{
  "name": "<% name %>",
  "description": "<% description %>"
}
}}}
{{{debug this}}}
<%={{ }}=%>

Note that you can do this as many times as you like throughout your template. Any time you run into something that conflicts, pick a new set of delimiters :)




回答2:


As described in this Question handlebars doesn't support changing the delimiters. But you can escape the double braces with a backslash like this:

HTML:

... \{{ myHandlbarsVar }} ...



回答3:


You can also assign Mustache.tags = ["[[", "]]"]; before your template compilation.

http://jsfiddle.net/fhwe4o8k/1/

e.g.

    $(function () {
        Mustache.tags = ["[[", "]]"];
        var template = $('#test').html();
        Mustache.parse(template);
        var rendered = Mustache.render(template, {test: "Chris"});
        $('#content-placeholder').html(rendered);
    });



回答4:


another option is create a helper for outputing curly brackets.

Handlebars.registerHelper('curly', function(object, open) {
    return open ? '{' : '}';
});

and then use it in the template like this:

<script id="template" type="text/x-handlebars-template">
    {{curly true}}{{name}}{{curly}}
</script>

which then outputs:

{Stack Over Flow Rocks}



回答5:


I just wanted slightly different approach. I have tried few other other ways and here are few things which I didn't like about them:

  1. Changing Angular default {{obj.property}} brackets to something else is a bad idea. Mainly beacause as soon as you start using third party components which are not aware of you non standard angular configuration, bindings in those third part components will stop working. Also worth mentioning that AngularJS team doesn't seem to want to go the route of allowing multiple binding notations, check this issue
  2. I quite like Mustache templates and don't want to switch the whole project to something else because of this small issue.
  3. Quite a few people recommend not to mix client and server side rendering. I don't fully agree, I believe if you are building a multipage website which has few pages with angular and some other which are static (something like about us or Terms and Conditions pages) it is perfectly fine to use server side templating to make maintaining those pages easier. But that said, for parts which are Angular you shouldn't mixing server side rendering.

Ok no my answer: If you are using NodeJS and Express you should be to the following:

Replace bindings {{}} in your angular part with something like {[{}]} (or something completely unique)

Now in you route add a callback to you render method:

app.get('/', function(req, res){
  res.render('home', {
    title: 'Awesome Website',
    description: 'Uber Awesome Website'
  }, function(err, html){
    var htmlWithReplacedLeftBracket = html.replace(/{\[{/g, '{{');
    var finalHtml = htmlWithReplacedLeftBracket.replace(/}\]}/g, '}}');
    res.send(finalHtml);
  });
});

This should allow you to use Mustache together with AngularJS. One improvement you could do is extract that method into a separate module to reuse across all routes.




回答6:


This is a good solution I have found for this type of problem where you can easily switch delimiters in the template settings in runtime:

http://olado.github.com/doT/

You can do the RegEx settings like this:

doT.templateSettings = {
  evaluate:    /\{\{([\s\S]+?)\}\}/g,
  interpolate: /\{\{=([\s\S]+?)\}\}/g,
  encode:      /\{\{!([\s\S]+?)\}\}/g,
  use:         /\{\{#([\s\S]+?)\}\}/g,
  define:      /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
  conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
  iterate:     /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
  varname: 'it',
  strip: true,
  append: true,
  selfcontained: false
};


来源:https://stackoverflow.com/questions/13944623/escape-double-braces-in-mustache-template-templating-a-template-in-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!