wycats/handlebars.js — pull request #787 by kpdecker (2014-08-12 19:19:30+00:00)
Title: Add remove-line whitespace control mode

Needed: a way of handling whitespace for producing correct output from readable templates in an environment where newlines and whitespace are significant. The problem is that the ~ whitespace handling does not work well when using handlebars to generate indent-sensitive text (such as CoffeeScript or YAML or markdown). Consider a little coffeescript example:

square = (x) ->
{{#if debugging}}
console.log('called square with ' + x)
{{/if}}
x * x
{{#if debugging}}
console.log('finished square')
{{/if}}
write square 20

The above ends up producing code with extra newlines (an issue for me because it's supposed to be instructional text read by students, and newlines in odd places are confusing to them). But then where would we put the ~ to fix the problem? The only solution is to think really carefully about spaces and write the template without ~ like this:

square = (x) ->
{{#if debugging}} console.log('called square with ' + x)
{{/if}} x * x
{{#if debugging}} console.log('finished square')
{{/if}}write square 20

Writing long templates like this is also pretty impractical for template writers (again, because it's all indent-sensitive.

Suggestion: syntax for "strip whitespace up to (and including) the following newline": -}}. It might be useful to do the left-hand version also (stripping whitespace to the left, not including the newline to the left), but it is not as important.

square = (x) ->
{{#if debugging-}}
console.log('called square with ' + x)
{{/if-}}
x * x
{{#if debugging-}}
console.log('finished square')
{{/if-}}
write square 20

Pretty again, and readably correct.

Note that mustache deals well with blocks opening and closing on "standalone lines", eliminating the spaces on those lines. That is terrific default behavior, no special tildes required - but that doesn't seem to be possible in handlebars.