Symfony2:如何根据权限隐藏 Twig 中的链接 [英] Symfony2: How to hide link in Twig based on permissions

查看:26
本文介绍了Symfony2:如何根据权限隐藏 Twig 中的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序显示了项目列表、项目详细信息页面和用于编辑这些项目的表单.这些是路线:

  • /- 项目列表
  • /project/42 - 查看项目(项目详细信息页面)
  • /project/42/edit - 编辑项目

只有其所有者可以编辑项目.

我已经实施了一个 Voter,以防止非所有者访问/project/42/edit.

现在,我还想从项目详细信息页面中隐藏编辑项目"链接.这样做的方法是什么?理想情况下,在 Twig 中,我想做类似

<前>{% if may_access(path('project_edit', { 'id': project.id })) %}<a href="{{ path('project_edit', { 'id': project.id }) }}">编辑项目</a>{% 万一 %}

我可以将此功能实现为 Twig 扩展,但可能已经存在类似的功能.

解决方案

函数 is_granted() 实际上 有第二个参数,允许我做我需要的事情:

<前>{% if is_granted("MAY_EDIT", project) %}<a href="{{ path('project_edit', { 'id': project.id }) }}">编辑项目</a>{% 万一 %}

我将此与控制器操作中的检查结合使用:

<前>公共函数 editAction(Project $project){if (!$this->get('security.context')->isGranted('MAY_EDIT', $project)) {$this->flash('你不能编辑这个项目');返回 $this->show($project);}//...}

这实际上与 nifr 在他对 Sonata 用户 - 自定义字段的安全性.我希望找到一种方法来自动调用选民并避免调用 isGranted().

如果你想看看完整的代码,它在我有发布在github的教程项目中.

My application shows a list of projects, project detail pages and forms to edit these projects. These are the routes:

  • / - list of projects
  • /project/42 - view project (project detail page)
  • /project/42/edit - edit project

Only its owner may edit a project.

I have implemented a Voter to prevent access to /project/42/edit for non-owners.

Now, I also want to hide the link "edit project" from the project detail page. What would be the way to do this? Ideally, in Twig, I would like to do something like

{% if may_access(path('project_edit', { 'id': project.id })) %}
  <a href="{{ path('project_edit', { 'id': project.id }) }}">edit project</a>
{% endif %}

I can implement this function as a Twig extension, but maybe a similar functionality already exists.

解决方案

The function is_granted() actually has a second parameter that allows me to do just what I need:

{% if is_granted("MAY_EDIT", project) %}
  <a href="{{ path('project_edit', { 'id': project.id }) }}">edit project</a>
{% endif %}

I use this in combination with a check in the controller action:

public function editAction(Project $project)
{
    if (!$this->get('security.context')->isGranted('MAY_EDIT', $project)) {
        $this->flash('You are not allowed to edit this project');
        return $this->show($project);
    }
    // ...
}

This is actually very similar to the approach that nifr used in his answer to Sonata User - Security on custom field. I was hoping to find a way to have the voter be called automatically and avoid the call to isGranted().

If you want to have a look at the complete code, it is in the tutorial project I have published in github.

这篇关于Symfony2:如何根据权限隐藏 Twig 中的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆