28 July 2011

How to theme Unordered (item) list with unique id or class assigned to all LI in Drupal

Drupal has many built in theme function to construct HTML elements, One of the frequently used is 'Item_list'. This theme function used to build a HTML ordered / unordered list.
<?php
$data = array('List 1','List 2', 'List 3');
$output = theme('item_list', $data);
?>
The Above use of theme function will output the <UL> and <LI> without any class or id.
For Example:
<ul >
<li > List 1 </li>
<li > List 2 </li>
<li > List 3 </li>
</ul>


If we need to have the output as below.
For Example:
<h3> Title </h3>
<ul class="my-list">
<li clase="list" id="list-1"> List 1 </li>
<li clase="list" id="list-2"> List 2 </li>
<li clase="list" id="list-3"> List 3 </li>
</ul>


Then our code will look like.

<?php
$items = array(
array('data' => 'List 1', 'Class' => 'list', 'id' => 'list-1'),
array('data' => 'List 2', 'Class' => 'list', 'id' => 'list-2'),
array('data' => 'List 3', 'Class' => 'list', 'id' => 'list-3')
);
$title = 'Title';
$output = theme('item_list', $items, $title, 'ul', array('class' => 'my-list'));
?>

In $items array for each item we defined an array with key data, class and id, this will be transformed to HTML.
Title parameter will be printed prefix to the UL tag, with header tag.
And 'ul' parameter decides the type ordered / unordered tag to be printed. defualt is UL
Last a class attribute to UL tag, you may add id or any HTML attribute to UL / OL tag, defining inside the array as key => value.
Refer this in Drupal API

5 comments: