I have a recursive data structure, basically a tree, where a node can have child nodes, etc. I am trying to create a JSON-like file of this structure. Use the #parse directive for this thought. In the context, I store the root of the node and the template name in templateName.
{ "name" = "$node.name", "value" = "$node.value"
The Apache speed documentation states that the #parse directive accepts only one argument .
In the examples, I saw the use of the #set directive before calling another template, but if the tree depth is higher than 2, this does not work, because the variable used in the #set directive is stored in the same context, so when moving from depth 1 to 2 the variable will be overwritten.
The reason for using #parse instead of a macro suggested by @Sergiu Dumitriu is that each node may be displayed differently, depending on its $node.type . I would like to have a template for each type, so that one person adding a template for a certain type should not bother with any other template, I mean, maybe this can be achieved by including the type property; but this means that all rendering methods will be defined in one file.
Is there a way to use Velocity to apply patterns to recursive data structures?
Solution Based on both answers by Sergiu Dumitriou, the final template is as follows:
#macro ( displayNode $node) { #set ( $parseNode = $node ) #set ( $parseTemplate = $parseNode.type + ".vm" ) #parse ( $parseTemplate ) #set ( $parseNode = $node ) #set ( $parseTemplate = "Common.vm" ) #parse ( $parseTemplate ) } #end
Common.vm has the structure shown in the question.
source share