Skip to content
This repository has been archived by the owner on Feb 12, 2018. It is now read-only.

Display Formatted Tree

kemo edited this page May 24, 2011 · 3 revisions

The code below will display a tree using kostache template or just a regular html string.
The kostache lines are marked if you want to remove them. also included below is the template_view and mustache file.

<?php
public function action_index() {
	$this->categories->rebuild_tree();  // make sure all nodes are tight.
	$cats = $this->categories->fulltree();
	$indent = "";
	$indent_margin = 4;
	$last_lvl = 1;
	$menu_str = "<ul>\n";
	$mycats = array();		//kostache
	$total_levels = array();	//kostache
	$i = 0;
	foreach($cats as $cat) {
		$addlevel = "";
		$minuslevel = "";		//kostache
		$minuslvls = array();	//kostache

		if($cat->lvl > $last_lvl) {
		$addlevel = 1;			//kostache
		$menu_str .= "<ul>\n"; 
		array_push($total_levels,1);	//kostache
		

		}
		if($cat->lvl < $last_lvl) {
		$menu_str .= "</ul>\n"; 
		$minuslevel = 1;		//kostache this whole loop is kostache only
		$j=0;
		for ($cnt = $cat->lvl; $cnt < $last_lvl; $cnt+=1) {
			array_push($minuslvls,1);
			array_pop($total_levels);
			//$minuslevel[$j] = 1;
			$j++;
		}
		}


		$mycats[$i] = array(				// kostache this array
			"cat_id" 	=> $cat->id, 
			"parent_id" 	=> $cat->parent_id, 
			"lvl"	 	=> $cat->lvl, 
			"lft" 		=> $cat->lft, 
			"rgt" 		=> $cat->rgt, 
			"catname" 	=> $cat->categoryname->name,
			"catcnt"	=> $cat->count(),
			"addlevel" 	=> $addlevel,
			"minuslevel" 	=> $minuslevel,
			"minuslvls"	=> $minuslvls
		); // end array.



		/*	this is another way to do your own indentation if you dont want to use <ul>, <ol>
		if($cat->lvl > 1) {
			$indent = str_repeat("&nbsp;",(($cat->lvl-1) * $indent_margin));
		}
		*/
		$menu_str .= "<li>{$cat->categoryname->name} ({$cat->count()})</li>\n";
		$last_lvl = $cat->lvl;
		$i++;
	} // end foreach.

	// kostache from here
	$this->storemenu_view->mycats = $mycats;
	$this->storemenu_view->total_levels = $total_levels;
	echo $this->storemenu_view;	
	// kostache to here

	echo $menu_str . "</ul>\n";
  } // end index.

============= storemenu.php - kostache view class ==============

<?php

class View_Storemenu extends View_Default {

	public $mycats;
	public $total_levels;
	public $minuslvls;

	public function tree_loop() {
	return new ArrayIterator($this->mycats);
	}

	public function poplvls() {
	return new ArrayIterator($this->total_levels);
	}

}
?>

=============
storemenu.mustache
=============

<ul>

{{#tree_loop}}
	{{#minuslevel}}
	{{#minuslvls}}
	</ul>
	{{/minuslvls}}
	{{/minuslevel}}

	{{#addlevel}}
	<ul>
	{{/addlevel}}

	<li> {{parent_id}}:{{catname}}</li>
{{/tree_loop}}

{{#poplvls}}
	</ul>
{{/poplvls}}

</ul>
Clone this wiki locally