1

I'am writing a plugin that has to return an array of data, however Twig does not seem to accept it if I return a PHP array. I don't want to use an explode in Twig to make it into an array.

I have seen in other plugins i can just call a function from twig like this.

{% set result = craft.winkelwagen.printWinkelWagen(currentUser.id) %}

{% for output in result %}
    {{ output }}
{% endfor %}

However, I get an array to string conversion error. Does anyone know the correct way to do this?

Thanks in advance.

4

Your plugin should be able to handle PHP arrays just fine.

craft/plugins/myplugin/variables/MyPluginVariable.php

function getArray()
{
    return array('hi', 'there');
}

craft/templates/template.twig

{% set result = craft.myPlugin.getArray() %}
{% for item in result %}
    {{ item }}
{% endfor %}

The error you're seeing is likely because output itself is an array. If you have devMode enabled you can try a {{ dump(output) }} inside your for-loop to see what it actually is / contains.

| improve this answer | |
  • i now only have this in twig {% set result = craft.winkelwagen.printWinkelWagen(currentUser.id) %} But it still gives the error however if i use print_r in php it outputs fine. – Bob van Velzen Oct 17 '17 at 13:40
  • Hang on - the only thing in your template is the 'set result = ...'-line - and you're still seeing a Twig-error about array to string conversion? If that's the case I suspect that something in one of your other templates (that this one is extending or including) is throwing the error - because there's no way a simple variable declaration should throw that error. – Fuglsetrampen Oct 18 '17 at 8:30

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.