0

I'm writing my first Drupal 8 theme.

Now for a block I need all some custom fields of the user. So that I can use it in my theme.

I create a theme file with collectionmanager_preprocess_html method.

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 *
 * Adds body classes if certain regions have content.
 */
function collectionmanager_preprocess_html(&$variables) {
// Load the current user.
$user = User::load(\Drupal::currentUser()->id());

// get field data from that user
$firstname = $user->field_first_name->value;
$lastname = $user->field_last_name->value;

$variables['custom_firstname'] = $user->field_first_name->value;
$variables['custom_lastname'] = $user->field_last_name->value;
}

If I'm correct I can access the variables in twig with {{custom_firstname}}. But it show always a null value. Can someone help me with this? I can't find my issue on this. The variable $firstname and $lastname contains the correct values.

3
  • What is the template name?
    – ya.teck
    Commented Nov 13, 2016 at 14:00
  • I need to use the variable in page.html.twig file.
    – JimmyD
    Commented Nov 13, 2016 at 14:04
  • if u need this variable in page.html.twig you should use preprocess_page instead of preprocess_html .
    – macherif
    Commented Jan 24, 2020 at 15:43

1 Answer 1

3

collectionmanager_preprocess_html() prepares variables for html.html.twig template. For page.html.twig the of the function name should be collectionmanager_preprocess_page(). The same pattern should be used for other theme hooks (view, block, field etc).

3
  • When I debug my source after changing the method name it gives me a ResourceNotFoundException.
    – JimmyD
    Commented Nov 13, 2016 at 14:14
  • That seems irrelevant to this issue.
    – ya.teck
    Commented Nov 13, 2016 at 14:21
  • I forgot to clear the cache after change the method name. Tnx
    – JimmyD
    Commented Nov 13, 2016 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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