Node field token to template Drupal 8/9

Another small post on the topic of the customization of the template of Drupal.

Suppose we have a separate content type for contact data. It is a thing when we process them through a custom module, but if we need to bring out only one or two fields in the pattern will help us a small post in the topic file theme-name.theme.

function theme-name_preprocess(&$variables, $hook) {
    $contacts_page = \Drupal::entityTypeManager()->getStorage('node')->load(2);
    $phone = $contacts_page->field_phone->value;
    $phone_clean = str_replace([' ','(',')','-'], '', $phone);
    $email = $contacts_page->field_email->value;
    $variables['phones'] = $phone;
    $variables['phones_clean'] = $phone_clean;
    $variables['email'] = $email;
}

In this example, the node id 2 we take the phone number and e -mail that we can bring out in the nodes in the pattern. 

For example, we need to display a link to your node--node-type.html.twig phone and mail:

<a href="tel:{{ phones_clean }}">{{ phones }}</a>
<a href="mailto:{{ email }}">{{ email }}</a>

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.