How to deal with hashes in keys, mustache.js?

I am trying to use mustache.js as a template system for the JSON data that I get from an external API. The problem is that the JSON object has keys that start with hashes, and I'm not sure how to deal with them. An example of an object (and complete simplification):

{ "items": [ "description": { "#cdata-section": "Description goes here" } ] } 

Mustache.js:

 var template = '{{#items}}' + '{{#description}}' + '{{cdata-section}}' + '{{/description}}' + '{{/items}}'; 

Obviously, it will not recognize the cdata section because it is not a key name. I cannot use {{#cdata-section}} because the hash symbolizes conventions or enumerations in Mustache.js. I also can not avoid this, {{\#cdata-section}} does not match anything.

Is there any way around this? Or do I need to pre-process the JSON object?

+4
source share
1 answer

Perhaps the best solution would be to modify mustache.js. Offensive line seems to be on line 106 with regex

 this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag 

Which corresponds to an open tag followed by ^ or # , then any number of spaces, then at least one character, then any number of spaces.

I'm not the best in regular expression, but an opening tag would follow with the statement that it cannot match {{\^ or {{\# :

 this.otag + "(?!\\\\)(\\^|\\#)\\s*(.+)\\s*" + this.ctag 

Four-time backslashes are interpreted by javascript as \\ + \\ = \\ , and then regex as \ + \ = \ . I have not tested this, but it should work.

If this works for you, consider opening a migration request for your change in the GitHub repository

EDIT: I missed the following: on line 152 , it looks like you need to add a similar statement. I will leave this as an exercise for the reader.

+1
source

All Articles