user3557031
user3557031

Reputation:

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.

Upvotes: 30

Views: 102716

Answers (4)

Georg
Georg

Reputation: 63

if need associative array:

{{info|json_encode(constant('JSON_PRETTY_PRINT'))|raw}}

Upvotes: 5

Developer
Developer

Reputation: 2895

You can user json_encode for serialize array as strig, then show pretty - build in twig

    {{ array|json_encode(constant('JSON_PRETTY_PRINT')) }} 
    

Upvotes: 13

JL M
JL M

Reputation: 1468

info is an array, so you should simple write

{{ info|join(', ') }}

to display your info array.

[info] is a array with one value : the array info.

Upvotes: 63

deceze
deceze

Reputation: 522042

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 %}

Upvotes: 16

Related Questions