Blog/ How to create custom item list in Drupal 7

By neerav.mehta Mon, 12/09/2013 - 19:38 Comments

Drupal uses a particular format for displaying all the lists (ul and ol) throughout the site. You can buid your own list using the Drupal theme function "theme_item_list". Here is the code for creating a custom list or nested list of items.

$title = t('My List');
$type = 'ul';
// The type of list to return (e.g. "ul", "ol").
$attributes = array(
  'id' => 'my-list',
  'class' => 'custom-class another-custom-class',
);

$items = array(
  '0' => array(
    'data' => 'Item 1',
    'id' => 'item_1',
    'class' => array('item-1')
  ),
  '1' => array(
    'data' => 'Item 2',
    'id' => 'item_2',
    'class' => array('item-2'),
    'children' => array(
      '0' => array(
        'data' => 'Sub Item 1',
        'id' => 'sub_1',
        'class' => array('sub-item-1')
      ),
      '1' => array(
        'data' => 'Sub Item 2',
        'id' => 'sub_2',
        'class' => array('sub-item-2')
      ),
    ),
  ),
  '2' => array(
    'data' => 'Item 3',
    'id' => 'item_3',
    'class' => array('item-3')
  ),
);

return theme_item_list(array(
  'items' => $items,
  'title' => $title,
  'type' => $type,
  'attributes' => $attributes
));

The Output will look like this:

<div class="item-list">
  <h3>My List</h3>
  <ul class="custom-class another-custom-class" id="my-list">
    <li class="item-1 first" id="item_1">Item 1</li>
    <li class="item-2" id="item_2">Item 2</li>
      <div class="item-list">
        <ul class="item-2" id="item_2">
          <li class="sub-item-1 first" id="sub_1">SubItem 1</li>
          <li class="sub-item-2 last" id="sub_2">SubItem 2</li>
        </ul>
      </div>
    </li>
    <li class="item-3 last" id="item_3">Item 3</li>
  </ul>
</div>

You can override "theme_item_list" in your template.php file to remove/change the class "item-list".

 

Ready to get Started?