【问题标题】:Freemarker - How to completely omit a field based on a condition?Freemarker - 如何根据条件完全省略字段?
【发布时间】:2022-10-13 16:41:40
【问题描述】:

我有以下 XML 模板

<Student>
    <firstName>${studentName}</firstName>
    <middleName>${middleName}</middleName>
    <lastName>${lastName}</lastName>
    <rollNo>${studentRoll}</rollNo>
    <marks>${marks}</marks>
</Student>

但是,middleName 是可选的,如果值为空白或 null,我根本不想发送此字段。含义,名字,姓氏,rollNo 和标记将出现,但中间名不存在。下面的例子:

<Student>
    <firstName>John</firstName>
    <lastName>Doe</lastName>
    <rollNo>FG62583</rollNo>
    <marks>76</marks>
</Student>

我们如何使用 Freemarker 实现这一目标?有什么方法可以设计模板以便可以省略字段?我对 Freemarker 很陌生,如果我问得太天真了,我很抱歉。

【问题讨论】:

    标签: java spring freemarker


    【解决方案1】:

    你可以做这样的事情

    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.
    
    

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 2019-01-28
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      相关资源
      最近更新 更多