gztomas gztomas - 3 months ago 15
HTML Question

How to make handlebars keep indentation when replacing a multi-line value?

Consider this handlebars template:

<div>
{{content}}
</div>


And the following data:

{
content: 'foo\r\nbar'
}


And the desired result (what I need):

<div>
foo
bar
</div>


But when compiling the handlebars template with the data I get this:

<div>
foo
bar
</div>


So, how to make handlebars keep indentation when replacing a multi-line value?
Of course, changing the data is not an option.

rd5 rd5
Answer

It's not possible. Handlebars didn't know anything about the place where data will be embedded. You have line break in data and you get line break in result, there is no and nowhere to get a tab (4 spaces) after foo, have just one line break.

One of the ways to deal with your problem is to use such helper, that knows about the indentation and process passed argument proper way.

See quick example.

Helper:

Handlebars.registerHelper('indent', function (data, indent) {
  var out = data.replace(/\n/g, '\n' + indent);
  return new Handlebars.SafeString(out);
});

used as:

{{indent foo '   '}}

will produce you multiline output with specified indentation.

Comments