Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 628
gztomas Avatar asked Sep 05 '14 15:09

gztomas


2 Answers

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 to true 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).

like image 113
Tobias J Avatar answered Oct 06 '22 19:10

Tobias J


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.

like image 23
raidendev Avatar answered Oct 06 '22 17:10

raidendev