Andrew Swan
Andrew Swan

Reputation: 13627

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?

Upvotes: 2

Views: 2354

Answers (2)

walrus
walrus

Reputation: 3145

You can use {$myMap[$someInvalidKey] ?: ''} to fall back to printing nothing (empty string) in the case that it's undefined.

Upvotes: 2

Matt
Matt

Reputation: 5428

I just verified that you can conditionally wrap it:

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

Upvotes: 3

Related Questions