{% if is_granted('view', post) %}
post
{% else %}
Permission denied
{% endif %}
对于将来,请提供更多背景。就像你在哪里打电话?我假设在控制器中?
我进一步假设它是在控制器的作用中。
从您的评论中得出的下一个假设是,如果用户具有访问权限并将其重定向,则要渲染模板。如果是这种情况,您可以做这样的事情:
public function fooAction()
{
// if it's not in a controller, but you have a container at $container
// you can call $container->get('security.authorization_checker')->isGranted('view', $post);
if (!$this->isGranted('view', $post)) {
return $this->redirect('https://example.com/denied');
// or if you have a route let's call it "app_denied"
//return $this->redirectToRoute('app_denied', ['param' => 'value', 'param2' => 'baz']);
}
// replace `view.html.twig` with your template
return $this->render('view.html.twig', [
'post' => $post,
]);
}
EDIT2:基于OP输入
您应该只能在树枝中使用
is_granted
。 您可以做类似的事情:
{% if is_granted('view', post) %}
Show the post here
{% else %}
Sorry you don't have permissions to access this!
{% endif %}
您唯一需要处理的是确保设置
post
如果您只想在某人没有访问权限的情况下显示消息,则可以使用:
{% if not is_granted('view', post) %}
Sorry you don't have permissions to access this!
{% endif %}
Edit3:OP询问了如何在树枝中设置
post
变量。 我再次在这里假设,所以您可能有一个控制器并使用类似的东西:
return $this->render('view.html.twig', [
'post' => $post,
'foo' => 'bar',
]);
在这种情况下,作为变量传递给树枝。
如果您有多个条目,请在post
foo
在树枝文件中,您可以使用
Post
循环循环循环。
$posts