Reputation: 5
I am looking for a way to avoid using this in a FreeMarker template :
<#if getName()??>
<Name>getName()</Name>
</#if>
Because I need to test many things.
Is there any way to do it by using, for example, a parameter in the tag? I don't want the tag to be written at all if the value is null. (So exclamation mark is not enough)
Upvotes: 0
Views: 295
Reputation: 9365
If all your tags follow the same basic structure:
<Tag>value</Tag>
you can use a macro, to save yourself some typing:
<#macro optional tag value=[]>
<#if value?has_content>
<${tag}>${value}</${tag}>
</#if>
</#macro>
and then apply it like this:
<@optional tag='User' value=user/>
<@optional tag='Name' value=name/>
resulting in the following output code:
<User>myuser</User>
<Name>myname</User>
if one of the properties is not defined the whole tag will be omitted from the output.
Upvotes: 1