Generating an Unordered List of Items

Problem

You want an unordered list of items in your Blade template.

Solution

Use the HTML::ul() method.

You simply pass the method a list of items. If you pass an associative array, only the array values are used.

{{ HTML::ul(array('a', 'b', 'c'))}}

This produces a simple list.

<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

If any of the elements are arrays, then a sub-list is generated.

// PHP code to generate $list
$list = array(
  'one',
  'two',
  array(
    'sub-one',
    'sub-two',
  ),
);
return View::make('thebladeview', array('list' => $list));

If the Blade template has the following:

{{ HTML::ul($list) }}

Then the following would be output.

<ul>
  <li>one</li>
  <li>two</li>
  <li>
    <ul>
      <li>sub-one</li>
      <li>sub-two</li>
    </ul>
  </li>
</ul>

If you want the sub-list to have a title, then have the array representing the sub-list have a key.

// PHP code to generate $list
$list = array(
  'one',
  'two',
  'three' => array(
    'sub-one',
    'sub-two',
  ),
);
return View::make('thebladeview', array('list' => $list));

If the Blade template has the following:

{{ HTML::ul($list) }}

Then the following would be output.

<ul>
  <li>one</li>
  <li>two</li>
  <li>three
    <ul>
      <li>sub-one</li>
      <li>sub-two</li>
    </ul>
  </li>
</ul>

If you want attributes to apply to the list, use an array as the second argument to HTML::ul().

{{ HTML::ul(array('a', 'b'), array('class' => 'mylist')) }}

Now the list has a class attribute.

<ul class="mylist">
  <li>a</li>
  <li>b</li>
</ul>

Discussion

A couple of notes.

  1. Any HTML entities in the list values are escaped.
  2. The second argument, $attributes, will only apply to the top level list. If you have sublists, they won't contain any attributes.
comments powered by Disqus