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 %}
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.
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_...')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.