TimTheEnchanter
TimTheEnchanter

Reputation: 3671

Generating JSON with Handlebars

I need to convert a small chunk of HTML in a handlebars template into a part of a JSON object. Here's the relevant portion of the Handlebars template:

<ul>
  {{#each props.items}}
    <li>
      <a>{{name}}</a>
    </li>
  {{/each}}
</ul>

The problem I'm facing is that I need the final output in the JSON object to be either an array of strings (one per line of the final code) OR a single string with no line breaks. Instead, I'm getting the whole final block as a single string but with line breaks - which makes the JSON invalid.

I don't own the Handlebars template or the JSON so I can't change either of those.

Here's what my code looks like currently:

var fileContents = Plugins.fs.readFileSync(hbsPath,  "utf8");

//Next line is my latest attempt to close each line with quotes, 
//inject a newline and start new line with quotes.
//It doesn't work - the newline isn't inserted.
//I've also tried \n\r, \r\n, \r

fileContents = fileContents.replace(/(\r\n|\n|\r)/gm, "\",\n\"");

var template = hbs.compile(fileContents);
var thisProps = {props: props};
return new hbs.SafeString(template(thisProps));

If I simply write the returned string to the console, it looks right, but when I create the JSON file with it, the unterminated strings are flagged as invalid.

Update: Here's where the JSON comes into the picture:

{
    "code" : [{{renderSnippet "MyPartial" MyModel }}]
}

This is the file that Handlebars processes and the partial inside the {{ }} is replaced with the string that comes out of Handlebars. That string is the problem - it includes line breaks which make it invalid JSON. I need to either make it a single string with no line breaks, or an array of strings with each line as a separate string.

Any pointers?

Thanks.

Upvotes: 0

Views: 4322

Answers (1)

t.niese
t.niese

Reputation: 40842

As I already said in the comment, Handlebars does not create JSON. Handlebars is a template engine targeting html, so it will only work well with html or languages having the same or similar escaping. You would need to store the result of {{renderSnippet "MyPartial" MyModel }} in an Object that you convert to JSON.

Something like that:

var renderSnippedTpl = Handlebars.compile('{{renderSnippet "MyPartial" MyModel }}');

var obj = {
   code : [renderSnippedTpl({/*required params*/})]
}

console.log( JSON.stringify(obj) );

Upvotes: 1

Related Questions