Drupal 8 tip: How to use a node field in the html.html.twig

So how do you get a value from a node to be output in the html twig template? Typically node elements are output only on the node template, block elements only on a block template, and so forth. But today, I needed to use the value of a new custom field in the html template. Normally that node variable is not available to the html twig file.

Step one: Add a theme_preprocess_html function in the .theme file:

function MYTHEME_preprocess_html(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['CUSTOM_VARIABLE'] = $node->field_MACHINENAME->value;
  }
}

Step two: Render the CUSTOM_VARIABLE in the html.html.twig file.

    {% if CUSTOM_VARIABLE %}
      {{ CUSTOM_VARIABLE|raw }}
    {% endif %}

In this instance, “raw” was really only alternative because the value needed to skip input format filtering. Other types of fields would use other twig handling. The point here is that it is possible to use a node variable in the html twig template.