DerekAllard.com

list helper extension for Code Ingiter

I was surprised that there weren’t list helper functions in the html helper, so I wrote one. Below is a list helper for the html helper to generate ordered and unordered lists from an array.

ol()

Creates an ordered list from an array, with optional list attributes. Usage is identical to ul() below.

ul()

Creates an unordered list from an array, with optional list attributes.

It supports unlimited levels of sub-lists, or nested lists.

ul (array [, $attributes])

The attributes can be a string (id=”menu”) or an array.

$animals = array(“cats”, “dogs”, “birds”);
$atts = array(
	‘id’=> ‘list’,
	‘class’=> ‘menu’

);

echo ul($animals);  // gives  

<ul>
	<li>cats</li>
	<li>dogs</li>
	<li>birds</li>

</ul>

echo ul($animals, $atts);  // gives  

<ul id=“list” class=“menu”>
	<li>cats</li>
	<li>dogs</li>

	<li>birds</li>
</ul>

echo ul($animals, ‘id=”animallist”‘);  // gives 

<ul id=“animallist”>
	<li>cats</li>

	<li>dogs</li>
	<li>birds</li>
</ul>

Nested lists

$cats = array(“Felix”, “Tony”, “Garfield”);
$animals = array(“cats”, $cats, “dogs”, “birds”);  // gives  

<ul>
	<li>cats
	<ul>
		<li>Felix</li>
		<li>Tony</li>

		<li>Garfield</li>
	</ul>
	</li>
	<li>dogs</li>
	<li>birds</li>

</ul>

Full list helper code

Copy and paste this into your html_helper.php

function ul($listitems, $attributes = ‘’)
{
	$list =“<ul”;
	if ($attributes != ‘’) {
		if (is_array($attributes)) {
			foreach ($attributes as $key => $val) {
				$list .= ” $key=\”$val\“”;
			}
		} else {
			$list .= ” $attributes”;
		}
	}
	$list .= “>
”;
	$list .= _drawList($listitems);
	$list .= “</ul>
”;
	return $list;
}  

function ol($listitems, $attributes = ‘’)
{
	$list =“<ol”;
	if ($attributes != ‘’) {
		if (is_array($attributes)) {
			foreach ($attributes as $key => $val) {
				$list .= ” $key=\”$val\“”;
			}
		} else {
			$list .= ” $attributes”;
		}
	}
	$list .= “>
”;
	$list .= _drawList($listitems);
	$list .= “</ol>
”;
	return $list;
}

function _drawList ($listitems)
{
	$items = ‘’;
	foreach ($listitems as $key => $val)	{
		// check if next item is an array or not
		$nextitem = next($listitems); 
		if (is_array($nextitem)) {
		$items .= “	<li>”.$val.“
”;
		}
		elseif (is_array($val)) {
			$items .= “	
	<ul>
”;
			$items .= _drawList($val).“
”;
			$items .= “	</ul>
	</li>
”;
		} else {
			$items .= “	<li>”.$val.“</li>
”;
		}
	}
	return $items;
} 

This entry was made on and filed into CodeIgniter.

Comments

No comments yet, be the first to write one!