2

I've created an EE plugin with a function that returns an array. e.g.

function things(){
    return array(
        array(
            'name'=>'bob',
            'age'=>40
        ),
        array(
            'name'=>'mary',
            'age'=>50
        )
    );
}

I cannot find any way to loop through this array with vanilla EE template tags. Can plugins only return strings? Is this really not possible or am I overlooking something simple? I'd like to do something like:

{foreach {things} }
    Name: {name}
    Age: {age}
{/foreach}

2 Answers 2

3

Your array is structured correctly, but you need to use the Template Class' Parse Variables method. The great thing about this method is that it allows you nest many levels deep if you like (allowing tag pairs within tag pairs within tag pairs), and you also get {count} and {total_results} automatically.

So in your plugin:

function things()
{
    $things = array(
        array(
            'name'=>'bob',
            'age'=> '40'
        ),
        array(
            'name'=>'mary',
            'age'=> '50'
        )
    );
    return $this->EE->TMPL->parse_variables($this->EE->TMPL->tagdata, $things);
}

Then in your template:

{exp:my_plugin:things}
    Name: {name}
    Age: {age}
{/exp:my_plugin:things}
0

Additional for previous answer modified for EE3:

In template (same):

{exp:addon_name:method_name}

   Name: {name}
   Age: {age}

{/exp:addon_name:method_name}

And in addon plugin need use ee()->TMPL:

$things = array(
        array(
            'name'=>'bob',
            'age'=> '40'
        ),
        array(
            'name'=>'mary',
            'age'=> '50'
        )
    );

    return ee()->TMPL->parse_variables(ee()->TMPL->tagdata, $things);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.