Wang Tang
Wang Tang

Reputation: 577

Check if FreeMarker #nested directive is empty

I want to output tags around a <#nested> directive in a macro, but only if it would actually output something. The actual use case is more complicated, this is just the broken down version. How do I check for existence of <#nested> content?

<#macro opt tagname>
    <#if (#nested)??>    <-- what do I need to put here
        <${tagname}>
            <#nested>
        </${tagname}>
    </#if>
</#macro>

Example 1

Template: <@opt hello />

Output: (empty)

Example 2

Template: <@opt hello>goodbye</@opt>

Output: <hello>goodbye</hello>

Upvotes: 0

Views: 260

Answers (1)

ddekany
ddekany

Reputation: 31162

You have to capture the nested content, and then print it if necessary. Like this (this assumes auto-escaping on):

<#macro opt tagname>
  <#local nestedContent><#nested></#local>
  <#if nestedContent?has_content>
    <${tagname}>${nestedContent}</${tagname}>
  </#if>
</#macro>

Without auto-escaping the #if changes to just <#if nestedContent != ''>.

Upvotes: 2

Related Questions