質問

Which is the best practice to generate in a template a dynamic menu (the menu will be present in all the other app's pages) depending on the user role? i'm using this in my main template:

{{render(controller('AcmeMainBundle:Sidebar:show'))}}  

and this is the controller

class SidebarController extends Controller {
    public function showAction() {

        $userRole = $this->getUser()->getRoles();        
        if (in_array("ROLE_ADMIN", $userRole)) {
            return $this->render('AcmeMainBundle:Sidebar:sidebarAdmin.html.twig');
        } else {
            return $this->render('AcmeMainBundle:Sidebar:sidebarUser.html.twig');
        }
    }
}

but i think it isn't good; what do you think? thanks!

役に立ちましたか?

解決

You can achieve this at the view level too. In the template, check the active user's role and hide/show menus depending on the role

{% if is_granted('ROLE_ADMIN') and not is_granted('ROLE_USER') %}

//Show admin stuff

{% else if is_granted('ROLE_USER') %}

//Show user stuff

{% endif %}

他のヒント

If you really want to use the same template for both and not have logic in the template, you can pass parameters to the render method to provide the elements that will be present in your menu.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top