有人可以解释一下如何在用户登录后向我的布局添加“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 Sylius\Bundle\ShopBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
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');
}
}
答案 0 :(得分:0)
你快到了。
我相信,如果您在用户注册时分配了ROLE_USER
,您的代码就会起作用。
如果只想检查用户是否登录,可以使用:
{% if app.user %}
# user is logged in
{% else %}
# user is not logged in
{% endif %}
答案 1 :(得分:0)
我确实使用了此{% if is_granted('IS_AUTHENTICATED_FULLY') %}
。对我来说,检查ROLE_USER并不总是有效。请注意,is_granted在当前会话中使用角色:因此,如果您具有新角色并且未登录/注销,则它将不起作用。请注意,正如文档所述:
IS_AUTHENTICATED_FULLY不是角色,但是有点像一个角色,并且 每个登录的用户都将拥有这个
答案 2 :(得分:0)
好,感谢@hoover_D和@ 113408的答复,但是经过反复试验,我设法解决了这个问题。
在我的security.yml文件中,更改了
sylius.security.shop_regex: '^/(?!admin|api/.*|api$|media/.*)[^/]++'
到
sylius.security.shop_regex: '/'
现在is_granted('ROLE_USER')在包括首页在内的每个页面上均可使用。