在布局中登录和注册链接



有人可以解释一下如何在我的布局中添加“Log in”“Register”链接,一旦用户登录,这些链接就会更改为‘Log Out’‘My Account’链接?

我尝试了以下代码,但它不起作用。

  {% if is_granted('ROLE_USER') %}
    <a class="dark-grey-small bold" href="{{ path('sylius_shop_account_dashboard') }}">{{ 'sylius.ui.my_account'|trans }}</a>
    <a class="dark-grey-small bold" href="{{ path('sylius_shop_logout') }}">{{ 'sylius.ui.logout'|trans }}</a>
  {% else %}
    <a class="dark-grey-small bold" href="{{ path('sylius_shop_login') }}">{{ 'sylius.ui.login'|trans }}</a>
    <a class="dark-grey-small bold" href="{{ path('sylius_shop_register') }}">{{ 'sylius.ui.register'|trans }}</a>
  {% endif %}

我的主页操作如下:

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types=1);
namespace SyliusBundleShopBundleController;
use SymfonyBundleFrameworkBundleTemplatingEngineInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
final class HomepageController
{
    /** @var EngineInterface */
    private $templatingEngine;
    public function __construct(EngineInterface $templatingEngine)
    {
        $this->templatingEngine = $templatingEngine;
    }
    public function indexAction(Request $request): Response
    {
        return $this->templatingEngine->renderResponse('@SyliusShop/Homepage/index.html.twig');
    }
}

你快到了。

我相信如果您在用户注册时分配ROLE_USER,您的代码将起作用。

如果您只想检查用户是否已登录,则可以使用:

{% if app.user %}
    # user is logged in
 {% else %}
    # user is not logged in
 {% endif %}

我确实使用这个{% if is_granted('IS_AUTHENTICATED_FULLY') %}。对我来说,检查ROLE_USER并不总是有效。请注意,is_granted使用当前会话上的角色:因此,如果您有新角色并且没有登录/注销,它将不起作用。请注意,正如文档所说:

IS_AUTHENTICATED_FULLY不是一个角色,但它有点像一个角色,而且 每个已登录的用户都将拥有此

好吧,感谢@hoover_D和@113408的回复,但经过大量的试验和错误,我设法解决了它。

在我的 security.yml 文件中,我更改了

sylius.security.shop_regex: '^/(?!admin|api/.*|api$|media/.*)[^/]++'

sylius.security.shop_regex: '/'

现在is_granted('ROLE_USER'(适用于每个页面,包括主页。

最新更新