创建带有可选嵌套内容的 freemarker 宏?

Ric*_*ick 3 freemarker

创建可以使用或不使用嵌套内容的宏的正确方法是什么?例如

<@myMacro/>
<@myMacro>my nested content</@myMacro>
Run Code Online (Sandbox Code Playgroud)

有这样的吗?或者是其他东西?

<#macro myMacro>
  <#if ??????>
    Before nested content
    <#nested/>
    After nested content
  <#else/>
    Nothing nested here
  </#if>
</#macro>
Run Code Online (Sandbox Code Playgroud)

Goo*_*ose 5

嵌套的内容被分配给一个变量,然后检查这个变量是否有任何内容。然后将该变量发送到输出,而不是使用另一个嵌套指令,以避免内容被处理两次。

<#macro myMacro>
    <#assign nested><#nested/></#assign>

    <#if nested?has_content>
        Before nested content
        ${nested}
        After nested content
    <#else/>
       Nothing nested here
    </#if>
</#macro>
Run Code Online (Sandbox Code Playgroud)

  • 确保在使用宏中的变量时使用 `&lt;#local .../&gt;` 而不是 `&lt;#assign .../&gt;`,否则你可能会遇到嵌套调用宏的问题(例如 `&lt;@ myMacro&gt; &lt;@myMacro/&gt; &lt;/@myMacro&gt;`) (3认同)