Image by Patrick Fore

How to style the Drupal content creation page

It worked in Drupal 7. What happened?

Rik de Boer
2 min readAug 4, 2019

--

To Drupal front-end magicians it is well-known fact that Drupal core inserts CCS class names in the <body> tag of the page. You can take advantage of these to change the style of the page, based on its content type, whether the user is logged in or not, and other attributes.

In Drupal 7 you can also use this mechanism to style the content creation page, /node/add/article, with a look and feel different from the content view page, e.g. /node/123.

The content view and content edit pages have, if the content type is article:

<body class=“… logged-in page-node node-type-article…”

While the content creation page has:

<body class=“… logged-in page-node page-node-add-article …”

The different body class makes it easy to style the page in a distinct fashion.

In Drupal 8 however, the second form is absent. The body tag classes for a node view page are identical to those for a node create (add) page and look something like this:

<body class=“… user-logged-in page-node page-node-type-article …”

So you cannot easily apply a different look to the node creation page.

The hook implementation code below fixes this.

If you already have SOME_MODULE with a mixed bag of tweaks and alterations for your site, you can drop this code in there. Otherwise create a new module.

function SOME_MODULE_preprocess_html(&$variables) {  if (empty($variables['node_type'])) {
$route = \Drupal::routeMatch();
if (($route->getRouteName() == 'node.add') &&
($node_type = $route->getParameter('node_type'))) {
$variables['node_type'] = $node_type->id() . '-add';
}
}
}

That should do it. At /node/add/article, you should now see the class name page-node-type-article-add appear in the body tag of the content creation page. Like this:

<body class=“… user-logged-in page-node page-node-type-article-add …”

Done.
And you won’t have to change a single Twig template for it!

One warning: don’t implement the above function as YOUR_THEME_preprocess_html(). It won’t work for our purpose. It has to be a module implementation, not a theme implementation.

--

--