【问题标题】:Creating a freemarker macro with optional nested content?创建带有可选嵌套内容的 freemarker 宏?
【发布时间】:2015-10-02 10:24:59
【问题描述】:

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

<@myMacro/>
<@myMacro>my nested content</@myMacro>

有这样的吗?还是别的什么?

<#macro myMacro>
  <#if ??????>
    Before nested content
    <#nested/>
    After nested content
  <#else/>
    Nothing nested here
  </#if>
</#macro>

【问题讨论】:

    标签: freemarker


    【解决方案1】:

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

    <#macro myMacro>
        <#assign nested><#nested/></#assign>
    
        <#if nested?has_content>
            Before nested content
            ${nested}
            After nested content
        <#else/>
           Nothing nested here
        </#if>
    </#macro>
    

    【讨论】:

    • 我未受过教育的直觉反应是怀疑这种方法,如果经常使用并围绕大块,可能会导致 freemarker 进行大量额外的临时内存分配,然后还需要大量额外的垃圾收藏。如果我的担忧是真正的担忧,任何人都可以发表评论吗?如果这是一个真正的问题,那么有没有办法避免这个问题?
    • 我认为你是对的。我想这取决于内容的频率和大小。我能想到的唯一其他方法是传递一个布尔参数,该参数用于决定是否显示嵌套指令周围的内容。
    • 确保在使用宏中的变量时使用&lt;#local .../&gt; 而不是&lt;#assign .../&gt;,否则您可能会遇到宏的嵌套调用问题(如&lt;@myMacro&gt; &lt;@myMacro/&gt; &lt;/@myMacro&gt;
    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2011-11-04
    相关资源
    最近更新 更多