user1830833
user1830833

Reputation: 181

Passing array values for loop TWIG+symfony

Before I go on with my code, I apologize in advance. I am just starting to learn twig and symfony.

Ok, so I have a controller that renders a simple html.twig. Where I am stuck is at the syntax of passing values in the for loop. Let me show you what I have:

Controller:

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
 /**
 * @Route("/", name="homepage")
 */
public function indexAction(Request $request)
{
    // replace this example code with whatever you need
    return $this->render('default/mine.html.twig', array(
        'user_name' => 'trolol',
        'one_li' => 'Learn Symfony',
        'two_li' => 'Learn Controller',
        'three_li' => 'Learn Twig',
        'four_li' => 'Eat',
        'nav' => array(
            '1':'11',
            '2':'22'
        )
    );
};
}

Twig:

<p>Welcome <h2>{{ user_name }}</h2></p>
    <p> To Do:
    <br />
    <ul>
        <li>{{ one_li }}</li>
        <li>{{ two_li }}</li>
        <li>{{ three_li }}</li>
        <li>{{ four_li }}</li>
    </ul>
    <br />
    <ul id="nav">
        {% for link,text in nav %}
            <li><a href="{{ link }}">{{ text }}</a></li>
        {% endfor %}
    </ul>

If I remove the loop part of the twig and controller, it works as expected. So now, I am stuck on figuring out the syntax for what I am trying to do. Any help on how I would accomplish what I am failing it?

Upvotes: 0

Views: 1030

Answers (1)

viktor77
viktor77

Reputation: 821

Instead of this

'nav' => array(
            '1':'11',
            '2':'22'
        )

You must use this:

'nav' => array(
            '1' => '11',
            '2' => '22'
        )

Your Twig code seems okay. You just can't define arrays in PHP the way you did.

EDIT: Looks like you have some typos. Try with this code:

<?php
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
     /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/mine.html.twig', array(
            'user_name' => 'trolol',
            'one_li' => 'Learn Symfony',
            'two_li' => 'Learn Controller',
            'three_li' => 'Learn Twig',
            'four_li' => 'Eat',
            'nav' => array('1' => '11', '2' =>'22')
        ));
    }
}

Upvotes: 1

Related Questions