0

I’m using symfony 4 voters and love how it works to grant or deny permission to a controller method.

What I’m trying to achieve now is to check if user has permission to see a specific block in my twig view. I have a voter called Web:

I’d like to do {% if isGranted(‘Web’) %}{% endif %}

Is this possible? otherwise I’d like to get the result of my voter in a variable from the controller that ‘ill pass to the view without necessary denying access to the method/page.

Is this possible?

Thanks.

Miles M.
  • 4,089
  • 12
  • 62
  • 108
  • 1
    The twig function is called [is_granted](https://symfony.com/doc/current/reference/twig_reference.html#is-granted). Terminology is also important. is_granted checks for a permission (aka role). So as long as you have a voter which deal with the web permission then your code should work. The voter name is irrelevant. – Cerad Feb 15 '19 at 13:19
  • interesting, actually it’s absolutely perfect for what I’m looking to do. Let me give it a try then thanks – Miles M. Feb 15 '19 at 13:55
  • That worked like a charm thanks! You should write an answer and I’ll accept it – Miles M. Feb 15 '19 at 14:09
  • 1
    Glad you got it working however this was basically a "read the manual" comment. Not the sort of answer encouraged by stackoverflow. – Cerad Feb 15 '19 at 14:15

1 Answers1

2

I suggest you export your block into an another template then you include it in your original template with the render function

{{ render(controller('App\\Controller\\MyController::myRenderMethod')) }}

then in MyController you can do :


use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
    public function myRenderMethod(Request $request)
    {
        if ($this->isGranted($attributes, $subject)) {
            //call your render method here
        }
    }
}