Drupal - How can I add an unescaped script tag and contents to a page?

Here's a simple way to do this with no additional modules required. For the sake of this example, I'm going to add this field to the Basic page content type that comes with the Standard installation profile.

First, let's create a new Text format. Go to admin/config/content/formats and click Add text format. I name the Text format JSON-LD and make it only available for Administrators. Be sure to leave all options blank and set Text editor to None, like so:

Step 1

Then, let's add a new field to the Basic page content type. Go to admin/structure/types/manage/page/fields/add-field and select Text (formatted, long). I name the field JSON-LD with an automatic machine name of field_json_ld.

Step 2

Then let's make sure we hide the field's label. Go to admin/structure/types/manage/page/display and make sure to set the Label to our new JSON-LD field to - Hidden -, like so:

Step 3

Now it's time to add the script to a new page. Go to node/add/page and fill in the Title and Body as you like. Here's the important bit: for the JSON-LD textarea, be sure to set the Text format to JSON-LD, like so:

Step 4

Now click Save and publish. Your node will look like this:

Step 5

Nothing special, right? Now let's take a look at our source code:

Step 6

Bingo!

Tags:

8