-->

Symfony2 User not defined in Twig Exception Contro

2019-09-01 02:06发布

问题:

I use my own action in order to handle exception in twig.

# Twig Configuration
twig:
    exception_controller:  MyBundle:Default:showException

The problem is that, i'm actually authenticated to my application, but in this special Controller the token is null.

Does someone have any idea to solve this problem, cause I use the user object in the twig template.

回答1:

From the docs:

One of the common pitfalls when designing custom error pages is to use the is_granted() function in the error template (or in any parent template inherited by the error template). If you do that, you'll see an exception thrown by Symfony.

The cause of this problem is that routing is done before security. If a 404 error occurs, the security layer isn't loaded and thus, the is_granted() function is undefined. The solution is to add the following check before using this function:

{% if app.user and is_granted('...') %}
    {# ... #}
{% endif %}