5

I'm attempting to create an unordered list using a render array in a custom block in a custom module.

I understand if I wanted to wrap things in div I could always use the 'container' type. Like so

    $content = [
        'container'    => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => ['container'],
            ],
            'item 1'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'p',
                '#value'      => 'Item 1',
            ],
            'item 2'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'p',
                '#value'      => 'Item 2',
            ],
        ],
    ];

But I'd like to be able to use an unordered list like so

    $content = [
        'container'    => [
            '#type'       => 'html_tag',
            '#attributes' => [
                'class'      => ['container'],
            ],
            '#tag' => 'ul',
            'item 1'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'li',
                '#value'      => 'Item 1',
            ],
            'item 2'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'li',
                '#value'      => 'Item 2',
            ],
        ],
    ];

What I'd like that to produce is

<ul class="container">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

But instead it produces

<ul class="container"></ul>
<li>Item 1</li>
<li>Item 2</li>   

Is there a way to create an unordered list using render arrays?

15

Use the theme 'item_list':

$content = [
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#title' => 'My List',
  '#items' => ['item 1', 'item 2'],
  '#attributes' => ['class' => 'mylist'],
  '#wrapper_attributes' => ['class' => 'container'],
];          

The wrapper_attributes are not used in all themes. In core this is classy and bartik, which is based on classy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.