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

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

问题描述

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天全站免登陆