0
votes

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.

1
The twig function is called 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
interesting, actually it’s absolutely perfect for what I’m looking to do. Let me give it a try then thanks - Miles M.
That worked like a charm thanks! You should write an answer and I’ll accept it - Miles M.
Glad you got it working however this was basically a "read the manual" comment. Not the sort of answer encouraged by stackoverflow. - Cerad

1 Answers

2
votes

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
        }
    }
}