H.W.
H.W.

Reputation: 353

Symfony2 check if user has access to url inside Twig

Is there a way in Symfony2 to check if user has access to specified url inside Twig template?

Something like this:

{% if user_has_access( '/some/url/to/access' ) %}
   <a href="{{ path( '/some/url/to/access' ) }}">You can come here</a>
{% endif %}

Upvotes: 4

Views: 1347

Answers (2)

mykiwi
mykiwi

Reputation: 1693

Like Paweł Brzoski explained, it's possible to create a custom twig function.

But in Symfony, the correct way is to use is_granted('ROLE_...')

Upvotes: 0

Thomas Shelby
Thomas Shelby

Reputation: 1370

If you want, you can create custom Twig extension for that.

More information about extension you can find in documentation.

http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Fox example: namespace AppBundle\Twig;

class AppExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('user_has_access', array($this, 'userHasAccess')),
        );
    }

    public function userHasAccess($user, $pathForCheck)
    {
        //your logic for check access. can returns true or false
        return true;
    }

    public function getName()
    {
        return 'app_extension';
    }
}

and in twig template

{% if user_has_access(app.user, 'path/to/check') %}
{% endif %}

This code can have error, because it's only prototype.

Upvotes: 1

Related Questions