For the future, please give more context. Like where are you calling this? I'm assuming in a controller?
I further assume it's in a action of a controller.
The next assumption derived from your comment is, that you want to render the template if the user has access rights and otherwise redirect him.
If this is the case, you could do something like this:
public function fooAction()
{
// if it's not in a controller, but you have a container at $container
// you can call $container->get('security.authorization_checker')->isGranted('view', $post);
if (!$this->isGranted('view', $post)) {
return $this->redirect('https://example.com/denied');
// or if you have a route let's call it "app_denied"
//return $this->redirectToRoute('app_denied', ['param' => 'value', 'param2' => 'baz']);
}
// replace `view.html.twig` with your template
return $this->render('view.html.twig', [
'post' => $post,
]);
}
Edit:
If you want a Exception being thrown, take a look at custom error pages. You can find a tutorial in the Symfony Documentation
Edit 2: based on OP input
You ahould be able to just use is_granted
in twig.
You could do something like:
{% if is_granted('view', post) %}
Show the post here
{% else %}
Sorry you don't have permissions to access this!
{% endif %}
The only thing you have to take care is, that the post
variable is set.
If you want to only display a message if someone doesn't have access rights, you could use:
{% if not is_granted('view', post) %}
Sorry you don't have permissions to access this!
{% endif %}
Edit 3: OP asked how to set the post
variable in twig.
I'm again assuming here, so you probably have a controller and use something like:
return $this->render('view.html.twig', [
'post' => $post,
'foo' => 'bar',
]);
In this case post
and foo
are passed as variables to twig.
If you have multiple Post
entries, let's say in $posts
and use something like
return $this->render('view.html.twig', [
'posts' => $posts,
]);
In the twig file, you can loop through the posts with a for
loop.
{% for post in posts %}
{% if is_granted('view', post) %}
Jup, show the post
{% else %}
Nope, don't show it
{% endif %}
{% else %}
There are no posts
{% endif %}
I'd recommend you to read the chapter about Templating
denyAccessUnlessGranted
points to a controller, and if the access is denied based on a voter, it will throw an exeption with the third parameter as "message". This then get's handled by Symfony if there's no exception handling in place. – wawa