google-closure-templates

In Soy (Closure) templates, how can I print an expression that might be undefined at runtime?


Let's say the template model contains a map called $myMap whose keys are unknown at compile time. If my template attempts to print a map entry using {$myMap[$someValidKey]}, all is fine. However if I try to print using {$myMap[$someInvalidKey]}, the template fails to render and instead throws this error:

In 'print' tag, expression "$myMap[$someInvalidKey]" evaluates to undefined.

How can I tell the template to simply print nothing if that expression is undefined, i.e. no such key exists in the map?


Solution

  • I just verified that you can conditionally wrap it:

    {if $myMap[$someInvalidKey]}{$myMap[$someInvalidKey]}{/if}