0

My site contains nodes which require different styles (and the occasional inline JS script) and the ability to adjust these styles through the interface rather than via code. These styles are currently implemented via a Code-only text field using <style> tags, which is not ideal. However for systemic reasons I can't place these node-specific styles in individual libraries.

How can I extract the contents of specific code-only fields and reposition this content as inline styles in the <head> of the page? I understand that this is not the preferred Drupal way, however I need a solution.

0

You could do this with a preprocess function. The code here works for full views only (it won't work e.g. in a view of multiple teaser nodes).

function THEME_preprocess_html(array &$variables) {
  $router = \Drupal::routeMatch();
  $node = $router->getParameter('node');
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }
  if ($node instanceof \Drupal\node\NodeInterface) {
    $variables['node_object'] = $node;
  }
}

Now you can use {{ node_object }} in your html.twig.twig, e.g.:

<html>
<head>
  {% if node_object %}
    {% if not node_object.field_css.isEmpty %}
      <style>
        {{ node_object.field_css.value|raw }}
      </style>
    {% endif %}
    {% if not node_object.field_js.isEmpty %}
      <script>
        {{ node_object.field_js.value|raw }}
      </script>
    {% endif %}
  {% endif %}
  ...

And yes... don't try this at home kids ;-P

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.