0
votes

I'm new to Drupal & Twig and all I need is in my custom theme a twig expression to output the current user's ID. I can't find anything in the template comments, only if a user is logged in true / false.

Is there a simple way to get the ID of the current user? I'm not sure how to implement custom methods in a theme.

thanks!

5

5 Answers

3
votes

Hello bobomoreno,

I would suggest you use the module Bamboo Twig.
The Bamboo Twig module provides some Twig extensions with some useful functions and filters aimed to improve the development experience.

You could then enable the sub-module Bamboo Twig - Loaders:

drush en bamboo_twig_loader -y

Finally, you will be able to use the Twig function bamboo_load_currentuser:

<!-- Get Current User -->
{% set user = bamboo_load_currentuser() %}
<div>{{ user.name.value }}</div>
<div>{{ user.uid.value }}</div>

You can find the complete official documentation there.

2
votes

In your theme find file yourthemename.theme and add following code:

function yourthemename_preprocess(&$vars, $hook)
{
  $vars['uid'] = \Drupal::currentUser()->id();
}

now if you edit your twig template for html, page, region, block, field, form element... you can use 'uid' token in your twig. It works for all hooks

1
votes

If you only need the ID in user.html.twig, it's {{ user.id }}

0
votes

Here's how D8 now works, in two lines of executable code:

<?php
// This code returns the current user ID.
$account = \Drupal::currentUser();
return $account->id(); 
0
votes

The display name is not a field you can configure in {{ content }}. You can get it directly from the user entity:

{{ user.displayname }}

Reference for the php method: AccountInterface::getDisplayName