1

I've created a couple of fields for the user in Drupal 8, example: first name. And i'm trying to print it in the home page (page.html.twig) but to no avail. I tried the following:

{{ user.field_first_name.0['#context']['value'] }}
{{ user.field_first_name.0.value }}                     
{{ user.field_first_name }} 

I even tried adding preprocess functions on mytheme.theme, and still it didn't work.

noting that the below works

{{ user.displayname }}

Appreciate any help given,

thanks

  • 2
    Don't print user values on page.html.twig. You simply can create a Views block for that, printing the current user in a certain view mode. – leymannx Feb 20 '20 at 9:42
  • Alright, will try that, is there a readon not to print user values on page.html.twig? – ram_griever Feb 20 '20 at 9:57
  • 1
    There is a reason why can't get user fields in a page template, this is because the page is not cached per user, only per user permissions. When you use a block, like @leymannx suggested, then only this block needs to be cached per user and not the entire page. – 4k4 Feb 20 '20 at 10:01
  • Rule of thumb is to avoid templating when possible. Only do this when you need markup changes like in a structural way. Page template is for printing regions. Other reason is you can invalidate the admin UI too easily with templating. That will result in maintenance overhead later. – leymannx Feb 20 '20 at 10:01
  • It's also worth mentioning that the user object isn't fully loaded by default, you would need to fully load it in a preprocess hook. Where, you could, if you wished, alter the caching. But a block would be a better approach, no need for code. – Alfred Armstrong Feb 20 '20 at 10:22
2

To print user fields on the page template create a Views block and place it in an existing region.

At best you first added a new view mode for User under https://example.com/admin/structure/display-modes/view and then on https://example.com/admin/config/people/accounts/display select the newly created view mode and place the fields you like to display.

Then create the view, have it display Users and in the very right under ADVANCED add a contextual filter for User ID. Select Provide default value and choose User ID from logged in user, save. Then in the very left under FORMAT > Show > User select the view mode you created earlier.


Don't print user values on the page template.

  1. page.html.twig is for printing regions.
  2. page.html.twig is cached per user role. Next user with the same role will get displayed initially cached values of another user.
  3. The user object with all field values isn't fully loaded by default, you would need to preprocess the user first.
  4. Templating should be done when you need to structurally change markup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.