简体   繁体   English

Symfony2:添加登录和注销选项html symfony2

[英]Symfony2: adding log in and log out option html symfony2

I'm using Symfony2. 我正在使用Symfony2。 I have a main twig template with a navbar where I want to have a pull-down menu with the options 'log in' or 'log out' depending on whether the user is logged in or not. 我有一个带有导航栏的主树枝模板,我想在其中有一个下拉菜单,其中包含“登录”或“注销”选项,具体取决于用户是否登录。 What is the best approach to accomplish this? 什么是实现此目标的最佳方法?

-By making a different, static main template for /admin/* with the log out option -通过使用注销选项为/ admin / *创建不同的静态主模板

-By checking whether the user is logged in or not inside each controller being called by the routing system and then passing the correct information to be shown to the twig template when it's time to render it -通过检查用户是否已在路由系统调用的每个控制器内登录,然后在需要渲染时将正确的信息传递给树枝模板。

-By calling a specific controller like buildNavbarAuthOption() from inside the template -通过从模板内部调用特定的控制器,例如buildNavbarAuthOption()

Last option doesn't seem the best one when trying to program using MVC, right? 尝试使用MVC进行编程时,最后一个选项似乎不是最佳选择,对吗?

Just use is_granted in your views: 只需在您的视图中使用is_granted

{% if is_granted('IS_AUTHENTICATED_FULLY') %}
    <a href="{{ path('name_of_logout_path') }}">Logout</a>
{% else %}
    <a href="{{ path('name_of_login_path') }}">Login</a>
{% endif %}

In your main template you could test if the variable app.user exists like this: 在您的主模板中,您可以测试变量app.user是否存在,如下所示:

{% if app.user %}
    {# display logout #}
{% else %}
    {# display login #}
{% endif %}

Or better yet, test if the current visitor has the minimum security role: 或者更好的方法是,测试当前访问者是否具有最低的安全性角色:

{% if is_granted('IS_AUTHENTICATED_REMEMBERED') %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM