1

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.

Community
  • 1
  • 1
TripodC
  • 19
  • 1
  • I also checked the syntax from this link here, http://drupal8notes.github.io/how-to-check-for-user-access-in-drupal-8/, but unsure how to include this in the view footer. The input format I'm testing with accepts PHP. – TripodC May 15 '17 at 01:42
  • What error do you get? [Edit] your question to include that detail – Dijkgraaf May 15 '17 at 07:27
  • I also depend on the template you are trying to modify. You may not have the user object in it. – MichaelB May 15 '17 at 13:06

2 Answers2

1

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 %}
Ronnie
  • 11,138
  • 21
  • 78
  • 140
0

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 %}
Ujjval Jha
  • 358
  • 2
  • 5