4

I am trying to teach myself Closure templates. I made a simple file simply.soy:

{namespace examples.simple}

/**
 * says hello to the world
 * @param? name Optional parameter specifying who you are greeting.
 */
{template .hiWorld}
  Hello
  {if $name}
   {$name}!
  {else}
   world!
  {/if}
{/template}

After I compile and call document.write(examples.simple.hiWorld();, however, the displayed string has no space between "Hello" and "world": Helloworld!

Why not?

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206

1 Answers1

6

Closure Templates handle line joining as follows:

Within the body of a template, you can indent the lines as much as you want because the template compiler removes all line terminators and whitespace at the beginning and end of lines, including spaces preceding a rest-of-line comment. The compiler completely removes empty lines that consist of only whitespace. Consecutive lines are joined according to the following heuristic: if the join location borders a template or HTML tag on either side, the lines are joined with no space. If the join location does not border a template or HTML tag on either side, the lines are joined with exactly one space.

To add a space in a Closure Templates where one is needed, use the special character command {sp}. In cases where an unwanted space is inserted, you may remove it using the command {nil}. For line joining examples, see features.soy.

simple.soy would become:

{namespace examples.simple}

/**
 * says hello to the world
 * @param? name Optional parameter specifying who you are greeting.
 */
{template .hiWorld}
  Hello{sp}
  {if $name}
   {$name}!
  {else}
   world!
  {/if}
{/template}
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
  • Thank you, that clarifies a lot! I'm still confused about {nil} though. If no spaces are inserted before or after template blocks, why do we need {nil}? What spaces are there to remove? – dangerChihuahua007 Jun 08 '12 at 18:39
  • 1
    @DavidFaux: I added a link to `features.soy`, which contains line joining examples using `{sp}`, `{nil}`. – Christopher Peisert Jun 08 '12 at 20:12
  • Thanks! Ok, so placing any template tag or HTML tag at the end of a line or at the beginning of the next line prevents a space. `{nil}` happens to be a template tag that does nothing. – dangerChihuahua007 Jun 08 '12 at 22:13
  • 1
    @DavidFaux: Correct, lines will be joined without a space if 1) the preceding line ends with either `>` or a template tag or 2) the following line starts with either `<` or a template tag ([Closure: The Definitive Guide](http://www.amazon.com/Closure-Definitive-Guide-Michael-Bolin/dp/1449381871), page 311). The character command `{nil}` changes line joining behavior where lines would be joined with exactly one space by joining the lines with no space. – Christopher Peisert Jun 08 '12 at 22:23