树枝中的 Symfony 选民

jee*_*van 1 php symfony twig

我已经实施了一个投票系统来检查用户是否可以查看他没有订阅的帖子。我在控制器中的一个动作中调用它。

$this->denyAccessUnlessGranted('view', $post, 'You do not have permission to 
view this post!');    
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

{% if is_granted('view', post) %}
    post
{% else %}
    Permission denied
{% endif %}
Run Code Online (Sandbox Code Playgroud)

waw*_*awa 7

对于未来,请提供更多背景信息。比如你在哪里称呼这个?我假设在控制器中?

我进一步假设它是控制器的一个动作。

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

如果是这种情况,您可以执行以下操作:

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,
    ]);
}
Run Code Online (Sandbox Code Playgroud)

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


编辑 2:基于 OP 输入

你应该可以只is_granted在树枝中使用。

你可以这样做:

{% if is_granted('view', post) %}
    Show the post here
{% else %}
    Sorry you don't have permissions to access this!
{% endif %}
Run Code Online (Sandbox Code Playgroud)

您唯一需要注意的是,post变量已设置。

如果您只想在某人没有访问权限时显示一条消息,您可以使用:

{% if not is_granted('view', post) %}
    Sorry you don't have permissions to access this!
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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

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

在这种情况下,postfoo作为变量传递给树枝。如果您有多个Post条目,让我们说$posts并使用类似

return $this->render('view.html.twig', [
    'posts' => $posts,
]);
Run Code Online (Sandbox Code Playgroud)

在树枝文件中,您可以使用循环遍历帖子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 %}
Run Code Online (Sandbox Code Playgroud)

我建议你阅读关于模板的章节