1

I have a blog and have two routes which redirect to my profile page and my "update profile" page

@Route("/profil/{slug}", name="profile")

@Route("/profil/{slug}/infos", name="profile_update")

And those routes have two links in my navbar which is a part of my base.html.twig template

So in my base.html.twig I did something like this

 <a href="{{ path('profile',  {'slug' : membre.slug }) }}" class="dropdown-item">Account</a>
 <a href="{{ path('profile_update',  {'slug' : membre.slug }) }}" class="dropdown-item">Update profile</a>

But it says "variable membre does not exist" :(

It only works in my profile route because in its template I also have those link inside the page so in the controller I did :

    /**
     * @Route("/profil/{slug}", name="profile")
     */
    public function profile(Membre $membre){

        return $this->render('blog/profile.html.twig', [
            'membre' => $membre
        ]);
    }

and it works, but base.html.twig has NO CONTROLLER it's just a "base" template so how am I suppose to tell it where the variable is from?

Thank you

1
  • If Membre is the logged-in user, you can use app.user in your template. Commented Aug 25, 2019 at 18:14

1 Answer 1

1

The problem is that base.html.twig is used by all controller actions, whether the user is set as template variable or not. One solution would be to only display these links when the member variable is set:

{% if membre is defined %}
    <a href="{{ path('profile',  {'slug' : membre.slug }) }}" class="dropdown-item">Account</a>
    <a href="{{ path('profile_update',  {'slug' : membre.slug }) }}" class="dropdown-item">Update profile</a>
{% endif %}

The only other option would be to always pass that variable to the template, which will be difficult since it requires some additional input.

Sign up to request clarification or add additional context in comments.

2 Comments

This condition is working but now instead of an error the links disappear since the variable is defined in only one function of my controller :/
Yes, if you always want the variable to be available you would need to provide the slug to each action, which does not seem feasible. You could also store the info in a session and then retrieve it in your template: {% if membre is not defined%}{% set membre = app.session.membre %}{% endif %}, but obviously that would mean that the session data needs to be up to date which might be difficult

Your Answer

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