Drupal 11: Check User Permission In Twig Template

The hasPermission() method on the user object can be used to check a permission in twig templates. The user object is sent to most twig templates so this method can be used freely.

For example, we can use this method to detect if the current user is able to create new pages of content, and then add a button to the twig template that links to the create Page form.

{% if user.hasPermission('create page content') %}
  <a href="/node/add/page">Add New Page</a>
{% endif %}

The value to pass to the usePermission() method is the machine name of the permission.

Add new comment

The content of this field is kept private and will not be shown publicly.