如何设置“登录"?作为匿名和“注销"的文本对于 twig 和 symfony2 中经过身份验证的用户? [英] How can I set "Login" as text for anonymous and "Logout" for authenticated users in twig and symfony2?

查看:18
本文介绍了如何设置“登录"?作为匿名和“注销"的文本对于 twig 和 symfony2 中经过身份验证的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜单,所有项目都显示给所有用户,我想在 symfony2 中向特定 ROLE 用户隐藏/显示特定项目.

I have a menu that all items appear for all users and I want to hide/show specific items to specific ROLE users in symfony2.

例如,我有

<ul class="navigation">
    <li><a href="{{ path('homepage') }}">{{ 'menu.home'|trans }}</a></li>
    <li><a href="{{ path('guest') }}">{{ 'menu.articles'|trans }}</a></li>
    <li><a href="{{ path('category') }}">{{ 'menu.categories'|trans }}</a></li>
    <li><a href="{{ path('user') }}">{{ 'menu.users'|trans }}</a></li>
    <li><a href="{{ path('logout') }}">{{ 'menu.logout'|trans }}</a></li>
</ul>

现在所有用户都会出现注销,即使他们没有登录.如何让树枝检查用户是否通过身份验证,然后选择

Now Logout appears to all users, even If they are not logged in. How can I make twig check whether a user is authenticated or not and then choose

<li><a href="{{ path('login') }}">{{ 'menu.login'|trans }}</a></li> ?

推荐答案

Twig中做如下检查:

{% if app.user %}
    <li><a href="{{ path('logout') }}">{{ 'menu.logout'|trans }}</a></li>
{% else %}
    <li><a href="{{ path('login') }}">{{ 'menu.login'|trans }}</a></li> 
{% endif %}

如果您有不同的角色,并且希望根据用户角色呈现页面的某些部分,您可以进行下一步检查:

In case if you have different roles and you'd like to render some parts of the page dependent on user role, you can do next check:

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

这篇关于如何设置“登录"?作为匿名和“注销"的文本对于 twig 和 symfony2 中经过身份验证的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆