我已经实施了一个选民系统,以检查用户是否可以查看他尚未订阅的帖子。我在控制器中的操作中称此为此。

问题描述 投票:0回答:1

{% 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, ]); }

Edit:
如果要抛出异常,请查看自定义错误页面。您可以在
php symfony twig
1个回答
7
投票

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

我建议您阅读有关templating的一章。
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.