java - Template recursive structure with apache velocity -
i have recursive data structure, tree, node may have child nodes , on. i'm trying generate json-like file of structure. thought of using #parse
directive. in context store root node , in templatename template's name.
{ "name" = "$node.name", "value" = "$node.value" #if ($node.childrens.size() > 0) , "childrens" = { #foreach ($child in $node.childrens) ## next statement not work #parse ($child.type + ".vm", $child) #end } #end }
the apache velocity documentation states #parse
directive only takes 1 argument.
in examples have seen use of #set
directive before calling template, if depth of tree higher 2 not work because variable used in #set
directive stored in same context when going depth 1 2 variable overwritten.
the reason use #parse
instead of macro suggested @sergiu dumitriu because each node may rendered in different way depending on it's property $node.type
. have template each type 1 person adding template particular type not have mess other template, mean, maybe achieved having switch on type property; implies ways of rendering defined in same file.
is there way of using velocity apply templates recursive data structures?
solution based on both answers sergiu dumitriu final template looks like:
#macro ( displaynode $node) { #set ( $parsenode = $node ) #set ( $parsetemplate = $parsenode.type + ".vm" ) #parse ( $parsetemplate ) #set ( $parsenode = $node ) #set ( $parsetemplate = "common.vm" ) #parse ( $parsetemplate ) } #end
the common.vm
has structure shown in question.
you should not use #parse
, since it's costly operation. define macro , use recursively instead.
#macro(displaynode $node) { "name" = "$node.name", "value" = "$node.value"## #if ($node.childrens.size() > 0), "childrens" = { #foreach ($child in $node.children) #displaynode($child) #end } #end } #end
if template name variable, can use #evaluate
construct template name dynamically:
#set ($d = '$') #foreach ($child in $node.children) #evaluate("#display${child.type}node(${d}child)") #end
Comments
Post a Comment