2
votes

I want to make a dynamic menu based on roles. Right now I am including the menu as a macro with a parameter(the role), but I am WRITING the role to test, and it works. I cannot get the value of the role from the controller at the template.

The thing is how to send the role of the user (already caught on the Controller) to the layout.

I have read a lot about the imposibility of creating global variables in twig, which could solve my problem.

This is my code:

# layout.html.twig #
{% block menu %}
   {{ userRole('admin') }}
{% endblock %}

That is working but, as I said, I have to WRITE the role. I need to get the value.

I have also tried sending the value as a parameter, but the thing is in the controller I am rendering to the content, and it extends the layout.

public function loginAction(){
 $ldaprdn  = $_POST['login'];     // ldap rdn or dn
 $ldappass =$_POST['pass'];

 $m = new Model();
 $params = array('user' => $m->login($ldaprdn,$ldappass),);

 $me = new Model();
 $user = array('user' => $me->getSettings(),);

 $this->render('::menu.html.twig',$user);
 return $this->render('intranetBundle:Default:landinga.html.twig', $user);

}

It's the only thing I can't solve by large.

Any possible solution? Maybe the architecture design is not the best or something. Or perhaps I can use some tool that I don't know...

The big thing is to obtain the value of the role in any template, from PHP to TWIG. Once done, the problem is solved.

4

4 Answers

1
votes

I see several ways of doing it

  1. You can use is_granted function to check roles in twig without variables from any controller. (simpliest)

  2. You can use a render controller to render a twig inside another twig (not recommended but usefull sometimes)

  3. you can redefine the block of the base template in the controller's template
  4. You can have all your controllers inhereting a global controller which pass all the variables needed in your base template
0
votes

Try this:

{% set var = 'inner variable' %}
My variable is {{ var }}
0
votes

what symfony version do you use?

there is method getUser() in Symfony\Bundle\FrameworkBundle\Controller\Controller and also app.user variable globally exists in twig templates. If "role" is the property in your User entity, you can get it via app.user.role in Twig

0
votes

So long as your user authentication is setup correctly, something like this will work fine:

{% if is_granted('ROLE_ADMIN') %} ... {% endif %}