1

I have this array:

$modules = array(
    'users',
    'submodule' => array(
        'submodule1',
        'submodule2',
    ),
);

My question is how can I access all the values and display it on html?

I have tried the following but no luck :

{% for key, module in modules  %}
        {% if modules.key is iterable %}
              {{ module }}
        {$ else %}
            {{ module }}
        {% endif %}
    {% endfor %}

Thanks!

1 Answer 1

1

If your array has only 2 levels, you can just do something close to what you did:

{% for module in modules %}
  {% if module is iterable %}
    {% for submodule in module %}
    <p>{{ submodule }}</p>
    {% endfor %}
  {% else %}
  <p>{{ module }}</p>
  {% endif %}
{% endfor %}

Will give you (with the context you given):

<p>users</p>
<p>submodule1</p>
<p>submodule2</p>

See fiddle


But if your array has an arbitrary number of levels, you should do some recursive using macros:

{% macro show_array(array) %}

    {% from _self import show_array %}
    {% for module in array %}

        {% if module is iterable %}
            {{ show_array(module) }}
        {% else %}
            <p>{{ module }}</p>
        {% endif %}

    {% endfor %}

{% endmacro %}

{% from _self import show_array %}
{{ show_array(modules) }}

With the following context (in YAML format):

modules:
  0: users
  submodule:
      0: submodule1
      1: submodule2
      subsubmodule:
        0: subsubmodule1
        1: subsubmodule2

This will give you:

<p>users</p>
<p>submodule1</p>
<p>submodule2</p>
<p>subsubmodule1</p>
<p>subsubmodule2</p>        

See fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.