[英]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? 在Symfony2中是否有办法检查用户是否可以访问Twig模板中的指定URL?
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. 如果需要,可以为此创建自定义Twig扩展。
More information about extension you can find in documentation. 有关扩展的更多信息,您可以在文档中找到。
http://symfony.com/doc/current/cookbook/templating/twig_extension.html http://symfony.com/doc/current/cookbook/templating/twig_extension.html
Fox example: namespace AppBundle\\Twig; Fox示例:命名空间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. 像PawełBrzoski解释的那样,可以创建自定义树枝功能。
But in Symfony, the correct way is to use is_granted('ROLE_...')
但是在Symfony中,正确的方法是使用
is_granted('ROLE_...')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.