2.7.2. Tree

Tree instruction is a kind of section, which generates hierarchical tree structures. Everything that works for sections, works for trees, too. The only difference is that here we use the {tree}, {treeelse} and {/tree} tags and that they require some additional information.

The information, how to display the particular situation is defined with three tags specified inside the tree instruction: {leaf}, {opening} and {closing}. The last one tells, how to close the depth level and return to the upper one. Below, we can see an example of displaying a tree as a HTML list.

Example 2.40. Sample tree rendering

<ol>
{tree=mytree}
	{leaf}
		<li>{$mytree.title}</li>
	{/leaf}
	{opening}
		<li>{$mytree.title}<ol>
	{/opening}
	{closing}
		</ol></li>
	{/closing}
{treeelse}
	<li>No tree provided.</li>
{/tree}
</ol>

Tree instruction can work with the Show known from sections.

Example 2.41. Trees and the show instruction

{show=mytree}
<ol>
{tree}
	{leaf}
		<li>{$mytree.title}</li>
	{/leaf}
	{opening}
		<li>{$mytree.title}<ol>
	{/opening}
	{closing}
		</ol></li>
	{/closing}
{/tree}
</ol>
{showelse}
	<li>No tree provided.</li>
{/show}

Other section features also affect tree rendering (for example, the dynamic section support works here, too).

If your templates render the various trees many times with the same layout, you can keep it in one place with the bindGroup. It is linked with the use tag written inside the tree instruction.

Example 2.42. Binding the tree layout from snippets

{bindGroup=treeSnippet}
	{leaf}
		<li>{$treeSnippet.title}</li>
	{/leaf}
	{opening}
		<li>{$treeSnippet.title}<ol>
	{/opening}
	{closing}
		</ol></li>
	{/closing}
{/bindGroup}							  
							  
							  
<ol>
{tree=mytree}
  {use snippet="treeSnippet"/}
{treeelse}
	<li>No tree provided.</li>
{/tree}
</ol>

Note that inside the bindGroup instruction, the tree blocks begin with the snippet name. It is automatically replaced with the correct name, when the snippet is put into the tree.

OPT tree support is the best to use with the modified preorder tree traversal algorithm to generate the trees. The algorithm calculates the "depth" parameter for each element and you have to provide it as one of the section blocks in order to make the tree be processed correctly. Now, OPT can count, whether the element is a leaf or whether it opens another level.

Example 2.43. The section data for the trees

$tree = array(0 =>
	array('title' => 'Element 1', 'depth' => 0),
		array('title' => 'Element 1.1', 'depth' => 1),
		array('title' => 'Element 1.2', 'depth' => 1),
			array('title' => 'Element 1.2.1', 'depth' => 2),
	array('title' => 'Element 2', 'depth' => 0)					
);
$tpl -> assign('tree', $tree);
$tpl -> parse('tree.tpl');