Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony variable does not exist in twig

Tags:

php

symfony

I have these two entities Users.php and sprovider.php and a UserController.php The thing that bothers me is the result when I try to render a template in this function.

 /**
 * @Route("/sproviderhome", name="sprovider_home")
 */
public function sproviderHomeAction(Request $request){

    $email = $request->get('email');
    $password = $request->get('password');

    $user= $this->getDoctrine()
        ->getRepository('AppBundle:Users')->
        findOneBy(array('email' => $email, 'password' => $password));

    $jobs = $this->getDoctrine()
        ->getRepository('AppBundle:jobs')
        ->findAll();

    if($user){
        return $this->render('home/sprovider.html.twig', array(
            'user' => $user,
            'jobs' => $jobs,
        ));
    }else{
        return $this->render('home/login.html.twig', array(
            'message' => "Sorry, you need to login first.",
        ));
    }
}

Result in sprovider.html.twig:

Variable "jobs" does not exist in home/sprovider.html.twig at line 8

sprovider.html.twig:

{% extends '::base.html.twig' %}

{% block body %}
    {% if user is defined %}
        <h2 class="page-header">Welcome {{ user.name }}</h2>
    {% endif %}

    {% for job in jobs %}
        {{ job.name }}
    {% endfor %}
{% endblock %}

The strange thing here is that $user exists but $jobs does not.

What I tried so far is to dump the jobs and there is no problem, the jobs are in the variable.

Another thing I tried is to pass a string like this:

return $this->render('home/sprovider.html.twig', array(
            'user' => $user,
            'jobs' => 'jobs',
        ));

Same result. Looks like its rendering only the first object which is strange because I am passing an array(). Am I missing something important? Can this have something to do with cache? I cleared both browser and doctrine cache, still nothing. I can't think of anything else to cause this. In other functions in the same controller I have had no problem rendering an array.

like image 997
Georgi Georgiev Avatar asked Dec 25 '22 07:12

Georgi Georgiev


1 Answers

You can make the loop safe in case there is no jobs variable defined placing a condition before.

{% if jobs is defined %}
    {% for job in jobs %}
        {{ job.name }}
    {% endfor %}
{% else %}
    No jobs found.
{% endif %}
like image 62
Marcos Labad Avatar answered Dec 27 '22 20:12

Marcos Labad