How To Determine If You’re On A Node In Drupal 8

PROBLEM
Preamble: If you don’t know how yet to embed media into Drupal, I recommend looking at how to embed stuff into Drupal 8 by Lullabot. It doesn’t go over everything (since you definitely need custom stuff) but it’s a good start.

We are using Entity Embed along with a few other contributed Drupal modules to be able to insert media into the WYSIWYG. I created a custom module in order to do this. I use hooks such as
HOOK_preprocess_entity_embed_container and HOOK_form_entity_embed_dialog_alter in order to get this functionality to work. I also have a template which outputs the media. Images output as img, files output as a link with file name and opens in a new window.

We were now asked to attach a content type in our content. Instead of creating a field, I wanted to be able to insert this content into the WYSIWYG.

After modifying my custom module which will render the entity, I ran into an interesting issue. I did not want to render the full entity in the WYSIWYG. First, it would render the whole thing and it would not put in the stuff we put into our .theme file. It didn’t look right.

I only want the entity to be rendered on the node screen (i.e. in our public facing theme… when it’s actually on a node).

The template in our custom module renders it in both the WYSIWYG and on the “node” side. So… how do I get it to only render on the “node” side?

SOLUTION
There are several states when it’s on the “node” side. I’m adding a variable in HOOK_preprocess_entity_embed_container which will tell the template to render the entity or else just say the name of the node it’s inserting. Just using
$node_info = \Drupal::routeMatch()->getParameter("node"); doesn’t work. $node_info is NULL on preview. However, if you also do:

$node_info = \Drupal::routeMatch()->getParameter("node");
if (empty($node_info)) {
	$node_info = \Drupal::routeMatch()->getParameter("node_preview");
}

then a:

if (gettype($node_info) == "object") {
	$variables["node_render"] = true;
}

which will tell the template to render the entity via the {{ children }}. So far this code hasn’t triggered any PHP or Drupal errors or warnings (fingers crossed).

Not sure if I’ll need this again but it’s probably handy to have since we are also using workbench, have nodes in draft, and have a preview.

Leave a Reply

Your email address will not be published. Required fields are marked *