纯粹在 FreeMarker 中实现有点尴尬,但它的完整语言足以做到这一点。假设这是在myutils.ftl
:
<#function safeSubstring s start end>
<#if s?length < start><#return ''></#if>
<#if s?length < end>
<#return s?substring(start)>
<#else>
<#return s?substring(start, end)>
</#if>
</#function>
<#macro printColumns cols>
<#list 0..999999 as i>
<#local start = i * 3>
<#local printedSomething = false>
<#list cols as col>
<#if start < col?length>
<#local printedSomething = true>
<#lt><#list cols as col>${safeSubstring(col, start, start + 3)?right_pad(8)}</#list>
<#break>
</#if>
</#list>
<#if !printedSomething><#break></#if>
</#list>
</#macro>
然后你可以这样做:
<#import "myutils.ftl" as u>
...
<@u.printColumns ['Helo', "How are you?", "Wassup"] />
如果您想要更高的性能,您可以考虑在 Java 中将其实现为 a TemplateDirectiveModel
(或 a TemplateMethodModelEx
),然后myutils.ftl
更改为<#assign printColumns = "com.whatever.PrintColumnsDirective"?new()>
.