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.
From the compile
reference:
preventIndent
: By default an indented partial-call causes the output of the whole partial being indented by the same amount. This can lead to unexpected behavior when the partial writes pre-tags. Setting this option totrue
will disable the auto-indent feature.
So, it follows that if you're able to set up your template so that content
is rendered by a partial, e.g.:
<div>
{{> ContentPartial}}
</div>
Then before it's rendered, register the ContentPartial
partial:
Handlebars.registerPartial('ContentPartial', '{{content}}')
then it will preserve indentation. (I actually discovered this feature when the auto-indentation screwed up formatting in my <textarea>
and I had to disable it).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With