问题
Suppose I have a template like the following:
start
{{#if data}}
data
{{/if}}
end
Regardless of what I pass to the template, it will always have two extra newlines:
start
data
end
Is there a way to have Handlebars not generate the newlines that the tags were occupying (without moving the tags themselves)? eg.
start
data
end
The reason why I want this is because there are cases (like in XML), where newlines are not desirable.
For example the following:
<parent>
{{#each}}
<child>{{.}}</child>
{{/each}}
</parent>
Will generate
<parent>
<child>foo</child>
<child>bar</child>
</parent>
Collapsing the {{#each}}, {{/each}} to a single line will cause Handlebars to generate lists on a single line as well. For example, this:
<parent>
{{#each}}<child>{{.}}</child>{{/each}}
</parent>
Will generate
<parent>
<child>foo</child><child>bar</child>
</parent>
So in order to generate XML without extraneous newlines, my templates end up looking something like this:
<parent>{{#each}}
<child>{{.}}{{/each}}
</parent>
Thanks!
回答1:
See this question. Try adding swung dash to the brackets, e.g., {{> partial ~}} instead of {{> partial}}, this will remove the newline. In your case, it would be:
start
{{#if data ~}}
data
{{/if ~}}
end
Which would compile to:
start
data
end
回答2:
The answer given here did not work for me using express-handlebars 3.0.0. What did work was a slight variation:
{{~#each children~}}
{{this}}
{{~/each~}}
I found this solution in this answer to a related question:
https://stackoverflow.com/a/23636497/54426
来源:https://stackoverflow.com/questions/21713227/how-to-remove-newlines-generated-by-handlebars