3
votes

Does anyone know how to loop through all parameters that are passed to a Twig template without knowing in advance what they are called? The {{ dump() }} function (which calls var_dump()) outputs something like this:

array(5) {
  ["foo"]=>
  bool(true)
  ["bar"]=>
  string(3) "Yes"
  ["baz"]=>
  int(99)
  ["subdata1"]=>
  array(1) {
    ["foo2"]=>
    bool(false)
  }
  ["subdata2"]=>
  array(1) {
    ["foo3"]=>
    int(5)
  }
}

I want to loop through all parameters which are not subdata1 or subdata2, so that I can output something like:

foo is true
bar is Yes
baz is 99

Preserving the data structure sent to the template is important, so I am looking for a solution on the Twig side of the pipe.

For the past two days I have trawled through the sparse Twig documentation trying to find a hidden gem which reveals how to do this, but turned up nothing.

3
is there any reason you can't do this before the parameters are given to the template? Twig uses the output buffer to provide nesting functionality, so naturally it makes no difference whether the parameters are manipulated before or after the rendering.Flosculus
I don't understand this. I am new to Twig. Perhaps you could expand in a full answer?Nicholas Shanks
Im just trying to get an idea of what you are trying to do first. Are you using Symfony, or Twig on its own?Flosculus
Twig on it's own. The extra tag is because I know Twig users are often Symphony users too.Nicholas Shanks

3 Answers

2
votes

You'll need to create your own function for this:

function get_other_context_vars($context)
{
    $vars = array();
    foreach ($context as $key => $value) {
        if (!$value instanceof Twig_Template && !in_array($key, array('subdata1', 'subdata2')) {
            $vars[$key] = $value;
        }
    }

    return $vars;
}

$environment->addFunction(new Twig_SimpleFunction('get_other_context_vars', 'get_other_context_vars', array('needs_context' => true)));

Usage:

{% for name, var in get_other_context_vars() -%}
    {{ name }} is {{ var }}
{%- endfor %}
1
votes

I would just inspect how the dump() helper works, then replicate similar behaviour in your custom extension.

0
votes

you can test if your value is an array

{% for value in values %}
    {% if value[0] is not defined %}
        {{ value }}
    {% endif %}
{% endfor %}

This solution works if you can know the keys of yours subdatas. The other solution is to create an other array in your controller using the is_array function to filter