2012-08-08 107 views
9

你好freemarkers大师freemarker的功能VS宏

我明白freemarker的函数和宏之间的区别是,宏可以打印到输出,但不能返回值,而函数可以返回值,但不能打印到输出。

嗯,我有一个问题,因为我需要同时打印和返回值:

我做递归树的探索与freemarker的,所以我有一个宏被称为recurvively。在探索树时,我需要将节点信息打印到输出,还需要计算并返回有关所探测节点的统计信息(例如探索节点的特定属性的总和)

如果我使用宏被反复调用,我可以打印节点信息但不能将统计数据返回给主叫实体。

如果我使用递归调用的函数,我可以返回统计信息,但不能在输出上打印节点信息。

一个解决方案可能是两次探索树,一次是打印节点信息,另一个是收集统计信息,但我讨厌使用这种不合理的解决方案。

有人可以提出更好的解决方案吗?

感谢

回答

0

可以存储在非#local变量的统计信息。像宏这样做<#assign treeStats = ...>,然后调用点:

<#import my="myutils.ftl"> 
... 
<@my.tree input /> 
<#assign stats = my.treeStats /> <#-- or whatever you want with my.treeStats --> 

啊,这是尴尬,但FreeMarker的没有出PARAMS返回二级结果。其实,你可以做循环变量一个黑客,但它也许是太混乱,再加上如果你真的需要一个身体,你不能用这一招:

<@my.tree input; res><#assign stats = res></@> 
1

或者你甚至可以使用全局变量存储为您的统计:

<#global stats = [] /> 

<#-- then when you call your function --> 
<#assign = method() /> 

<#function method param = ""> 
    <#-- do something and before you return you push the stats to the global variable, if you choose my approach of "merging" sequences, be careful that you wrap the new stats item also in a sequence or it will fail miserably =) --> 
    <#global stats = stats + [{"statvar1": 10, "statvar2": 30}] /> 

    <#return whateveryoulike /> 
</#function>