Reputation:
I'm looking for the proper syntax with a Drupal 8 conditional display of a link. I've been reading the twig documentation, and it's a significant jump from the PHP templating days so it's slow going. I need to conditionally display a link within the footer of a view.
In the past, this would be straightforward, i.e:
<?php global $user;?>
<?php if (user_access('administer nodes')):?>
<div class="foo"><a href="/">Shorthand link for admins</a></div>
<?php endif;?>
Getting this to work in Twig has been difficult as I'm unfamiliar with the syntax. Do I need to declare global user in some capacity? From this link here, Symfony 2: How do I check if a user is not logged in inside a template?, it seems that all I'd need to do is:
{% if is_granted('ROLE_ADMIN') -%}
<div class="foo"><a href="/">Shorthand link for admins</a></div>
{% endif %}
But I get an error when trying to submit that. Is ROLE_ADMIN not defined? How do I get the Symphony? (correct?) roles as defined within the D8 installation? I'm not sure what I'm doing wrong. Any assistance is appreciated.
Upvotes: 1
Views: 765
Reputation: 11198
If you need to check a specific permission try
{% if user.hasPermission('administer nodes') %}
<div class="foo"><a href="/">Shorthand link for admins</a></div>
{% endif %}
Upvotes: 1
Reputation: 358
If you try to check the current user is administer in TWIG file , you can use
{% if is_admin %}
<div class="foo"><a href="/">Shorthand link for admins</a></div>
{% endif %}
Upvotes: 0