How can I set “Login” as text for anonymous and “L

2019-07-11 05:09发布

问题:

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.

For example, I have

<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> ?

回答1:

In Twig do following check:

{% 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 %}


标签: symfony twig