我的应用程序显示了项目列表、项目详细信息页面以及用于编辑这些项目的表单。这些是路线:
- /- 项目列表
- /project/42 - 查看项目(项目详细信息页面)
- /project/42/edit - 编辑项目
只有其所有者才能编辑项目。
我已经实现了投票器来阻止非所有者访问/project/42/edit。
现在,我还想从项目详细信息页面隐藏“编辑项目”链接。该怎么做呢?理想情况下,在 Twig 中,我想做类似的事情
{% if may_access(path('project_edit', { 'id': project.id })) %} <a href="{{ path('project_edit', { 'id': project.id }) }}">edit project</a> {% endif %}
我可以将此功能实现为 Twig 扩展,但也许类似的功能已经存在。
最佳答案
函数is_granted()实际上has a second parameter这使我能够做我需要做的事情:
{% if is_granted("MAY_EDIT", project) %} <a href="{{ path('project_edit', { 'id': project.id }) }}">edit project</a> {% endif %}
我将其与 Controller 操作中的检查结合使用:
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); } // ... }
这实际上与 nifr 的方法非常相似。用于他对 Sonata User - Security on custom field 的回答。我希望找到一种方法来自动调用投票者并避免调用 isGranted()。
如果你想看完整的代码,它在我的教程项目中published in github .
关于security - Symfony2 : How to hide link in Twig based on permissions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17085130/