gpt4 book ai didi

php - Twig 上的 Symfony 选民

转载 作者:行者123 更新时间:2023-12-04 16:05:49 25 4
gpt4 key购买 nike

我已经实现了一个投票系统来检查用户是否可以查看他没有订阅的帖子。我在 Controller 的一个 Action 中调用它。

$this->denyAccessUnlessGranted('view', $post, 'You do not have permission to 
view this post!');

如果投票者返回 true,则将其重定向到 twig 模板。

如果相同的模板返回 false 并显示消息“您无权查看此帖子!”,我该如何渲染相同的模板? ?

编辑得更清楚:我不希望用户通过更改 url 中的帖子 ID 来查看他未订阅的帖子。所以,我已经实现了选民来检查这一点。如果 voter 返回 true,则呈现 twig 模板,否则将显示没有模板的消息。我希望在模板中显示此消息。

我想在我的 Twig 模板中使用这样的东西:

{% if is_granted('view', post) %}
post
{% else %}
Permission denied
{% endif %}

最佳答案

对于 future ,请提供更多背景信息。比如你在哪里叫这个?我假设在 Controller 中?

我进一步假设它在 Controller 的操作中。

从您的评论中得出的下一个假设是,如果用户具有访问权限,您希望呈现模板,否则会重定向他。

如果是这种情况,你可以这样做:

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

编辑:如果您想抛出异常,请查看自定义错误页面。您可以在 Symfony Documentation 中找到教程。


编辑 2:基于 OP 输入

你应该可以在 twig 中使用 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 %}

编辑 3:OP 询问如何在 twig 中设置 post 变量。我在这里再次假设,所以你可能有一个 Controller 并使用类似的东西:

return $this->render('view.html.twig', [
'post' => $post,
'foo' => 'bar',
]);

在这种情况下,postfoo 作为变量传递给 twig。如果您有多个 Post 条目,假设在 $posts 并使用类似

return $this->render('view.html.twig', [
'posts' => $posts,
]);

在 twig 文件中,您可以使用 for 循环遍历帖子。

{% for post in posts %}
{% if is_granted('view', post) %}
Jup, show the post
{% else %}
Nope, don't show it
{% endif %}
{% else %}
There are no posts
{% endif %}

我建议您阅读 the chapter about Templating

关于php - Twig 上的 Symfony 选民,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com