I want to show custom-node-edit-links in node-teaser and nodes. But I can't check the actual access permission of the logged in user. In drupal-7-node-templates this was possible via php, but what can I do to check these permissions in Drupal 8 node-templates (via twig).

Thanks in advance

Comments

Jeff Burnz’s picture

You can check for a permission:

    {% if user.hasPermission('administer nodes') %}
      ... do something
    {% endif %}

This is sort of mentioned in the node template doc comments:

 * - node: The node entity with limited access to object properties and methods.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - node.getCreatedTime() will return the node creation timestamp.

What it doesn't mention is the entire user object is in the $variables array, and you can use those same get, has and is methods - debugging with Devel in preprocess and you can easily discover these methods.

kay.beissert’s picture

Thank you, this sollution works perfect. You saved me hours of trial and error.

hellobank’s picture

Hi Jeff,

How to check a visit if logon or not?

thanks in advance.

hellobank’s picture

Got it:

{% if logged_in %}
... do something
{% else %}
... do something
{% endif %}
VarunKrSingh’s picture

Thanks Jeff,
Can we use something similar for roles_target_id as i have multiple custom user types and need to put different conditions on based of same in TWIG file.

nielsvoo’s picture

Thanks, this should be in de right direction for fixing my challenge.

Is it also possible to check the users ip adress and when this is in the right range a body class will be set and the frontpage is set to another location?

What I like to accomplisch is something like:

$ip = ip current user;
$iprange = 1.2.3.32/27;

{% if logged_in %} and {% if $ip <> $iprange %}
… frontpage = '/front2'
… bodyclass = 'red'
{% else %}
... do something
{% endif %}

I found this link, https://github.com/symfony/http-foundation/blob/master/IpUtils.php#L36 maybe there is already a method in the Symfony framework?

Thanks in advance.