BS Blog

Drupal 8: Using Entity Embed to place reusable inline scripts into WYSIWYG content

Published Jun 12, 2018 | 2 Comments

First off, full disclosure I hate what I’m about to tell you. I loathe seeing the PHP Filter Module installed or clients with tons of Inline <style> or <script> tags riddled throughout their content fields; however, I also understand that sometimes there is a use case for such things (Not PHP filter though, seriously f*ck that sh*t).

Annyyyhoo, here is a way for you to include reusable inline code into your WYSIWYG not only without disabling formatting or filter plugins, but also placing it anywhere inside the content with only people with appropriate permissions able to create/edit the script.

NOTE: Before starting this tutorial, ensure you have the Entity Embed module installed

Step one: create a new new text editor format with no editor or filter plugins selected, this also allows you to set the role(s) who should be able to add scripts.

Add Text Format

Then create a custom block type (I’ve called mine “Inline Script”), and delete the default Body field. Then Add a new field (“Markup”) as formatted text, long and set the default text format to the one you just created. (You’ll also want to edit the display to hide the field label.)

Inline Script

Next you need to create a new Entity Embed button. Navigate to /admin/config/content/embed and click on “Add Embed Button”. Select your new block type as the target.

Embed Button

Once created, you’ll need to drag the new button to your WYSIWYG editor toolbar for the text format(s) that content editors will use.

Text Editor

Now a user with the appropriate permissions can add blocks with reusable scripts in them.

Script Block

And content editors can now embed those scripts by embedding them into the content at any given point.

Embed it

Note that the script may or may not affect your editor as well depending on the context of the script.

Select Embed

Now when the page is rendered, you can see the script is run at that point in time just as if it was added directly into the content, but without hacking CKEditor or allowing content editors to brutally ruin the site or it’s security. Yay!

Script Embed

Fin.