Search code examples
phparraysstringfor-looptwig

Twig Array to string conversion


This is probably relatively easy to do, but I'm new to twig and I'm frustrated.

I'm adapting code from this answer: https://stackoverflow.com/a/24058447

the array is made in PHP through this format:

$link[] = array(
       'link' => 'http://example.org',
       'title' => 'Link Title',
       'display' => 'Text to display',
);

Then through twig, I add html to it, before imploding:

    <ul class="conr">
        <li><span>{{ lang_common['Topic searches'] }} 
        {% set info = [] %}
        {% for status in status_info %}
            {% set info = info|merge(['<a href="{{ status[\'link\'] }}" title="{{ status[\'title\'] }}">{{ status[\'display\'] }}</a>']) %}
        {% endfor %}
        
        {{ [info]|join(' | ') }}
    </ul>

But I'm getting:

Errno [8] Array to string conversion in F:\localhost\www\twig\include\lib\Twig\Extension\Core.php on line 832

It's fixed when I remove this line, but does not display:

{{ [info]|join(' | ') }}

Any ideas how I can implode this properly?

** update **

Using Twig's dump function it returns nothing. It seems it's not even loading it into the array in the first place. How can I load info into a new array.


Solution

  • You shouldn't really be building complex data structures inside of Twig templates. You can achieve the desired result in a more idiomatic and readable way like this:

    {% for status in status_info %}
        <a href="{{ status.link }}" title="{{ status.title }}">{{ status.display }}</a>
        {% if not loop.last %}|{% endif %}
    {% endfor %}