简体   繁体   English

我如何告诉自由标记跳过<sep>列表迭代中的指令?

[英]How do I tell free marker to skip a <sep> directive in a list iteration?

I am trying to iterate over a JSON object in a <#list> iteration in Freemarker and write out the same JSON in a different form.我试图在 Freemarker 的 <#list> 迭代中迭代 JSON 对象,并以不同的形式写出相同的 JSON。 For some conditions, I'd like to skip over the iteration and not write out anything, but Freemakrer still writes out the comma because I use the separator directive: <#sep>,</#sep> .对于某些情况,我想跳过迭代而不写出任何内容,但 Freemakrer 仍然写出逗号,因为我使用了分隔符指令: <#sep>,</#sep>

For example例如

"<#list .data_model as key, value>" +
    "<#if key == 'someVal1' || key == 'someVal2' || value?is_hash>" + //do nothing for these
    "<#else>" +
        "\"${key}\":\"${value?json_string?json_string}\"<#sep>,</#sep>" +
    "</#if>" +
"</#list>"

The output is something like:输出类似于:

{"aval1":"1",,"aval2":["item"], ...}

Notice the duplicate commas.注意重复的逗号。

In other places I have implemented some special logic where I write out a comma for the previous item, so long as the current item is not the first item.在其他地方,我已经实现了一些特殊的逻辑,我为前一项写了一个逗号,只要当前项不是第一项。 The logic works but seems weird to have to duplicate.该逻辑有效,但必须复制似乎很奇怪。

Are there any Freemarker built-ins for this kind of situation?是否有针对这种情况的 Freemarker 内置插件?

<#sep> (and ?has_next , ?index , etc.) assumes that you will render all the items in the value that you list. <#sep> (以及?has_next?index等)假设您将呈现您列出的值中的所有项目。 Specifically, #sep decides based on if there will be a next item, and not based on if there was a previous item.具体来说, #sep根据是否有下一个项目来决定的,而不是根据是否有前一个项目来决定的。 (Looking back doesn't work in general, as you can't always postpone printing the separator for the next iteration, like consider <#sep>,</#sep></span> .) So either you pre-filter that map in Java, or you will need a variable to keep track if an element was already printed, and then print the separator before the current item. (回顾过去一般是行不通的,因为你不能总是推迟打印下一次迭代的分隔符,比如考虑<#sep>,</#sep></span> 。)所以要么你预过滤在 Java 中映射,否则您将需要一个变量来跟踪元素是否已打印,然后在当前项目之前打印分隔符。

BTW, 2.3.29 (released within a week) has ?filter to address this kind of problem, however, that only supports filtering list-like values for now, not map-like values yet (maybe in 2.3.30).顺便说一句,2.3.29(一周内发布)有?filter来解决这种问题,但是,目前只支持过滤类似列表的值,不支持类似映射的值(可能在 2.3.30 中)。 So even with 2.3.29 you had to list the keys, and then get the value by key in the filter expression and then inside the nested content... not very nice.因此,即使使用 2.3.29,您也必须列出键,然后在过滤器表达式中通过键获取值,然后在嵌套内容中获取值......不是很好。

Found a way to work around:找到了解决方法:

"<#assign x=false><#list .data_model as key, value>" +
"<#if key == 'someVal1' || key == 'someVal2' || value?is_hash>" + //do nothing for these
"<#else>" +
    "<#if x>,</#if>\"${key}\":\"${value?json_string?json_string}\"<#assign x=true>" +
"</#if>" +
"</#list>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM