Search code examples
foreachexpressionengine

For each loop in ExpressionEngine template?


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}

Solution

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