Jonathan Lee
Jonathan Lee

Reputation: 61

How to get rid of extra space in handlebars.js when value is undefined (w/o using #if)?

I have some content like this:

<div>{{someText}} {{someText2}} more text</div>

I've noticed when someText2 is undefined, there is an extra space between {{someText}} and "more text".

I know one solution is I could use an {{#if}} to say:

{{#if someText2}} 
     <div>{{someText}} {{someText2}} more text</div> 
{{else}}
     <div>{{someText}} more text</div>  
{{/if}}

problem is, this file is provided to another handlebars file, all this content is being injected into {{{text}}}. I tried the above approach and it doesn't work. I haven't tried using {{#unless}} or other condition keywords, but I'd assume if this doesn't work then that approach won't either.

If anyone has another approach I could try I'd really appreciate it. Thank you for reading

Upvotes: 0

Views: 168

Answers (1)

Laurent Dhont
Laurent Dhont

Reputation: 1062

This is because you have 2 spaces 1 before someText2 and 1 after. You could solve this by appending a space in your if block:

<div>{{someText}} {{#if someText2}}{{someText2}} {{/if}}more text</div>

Note that there is no space before "more text" and a space after {{someText2}}, so only if someText2 is defined there will be a space.

Upvotes: 1

Related Questions