Submitted by chrishu on Tue, 09/10/2013 - 16:26

Introduction

Occaisionally you are given some HTML and/or Javascript code to paste into your webpage, source code to implement a widget of some sort (Twitter being an example). Usually Drupal has module that fits the bill and allows you to configure a few options to automatically generate the code and dynamically place it on the page for you. Often there is further functionality to tie into related APIs or configuration. 

Drupal 8 doesn't really have that yet. it is OK for a developer who has access and can paste directly in a theme template or do something a bit more elegant, but what otherwise?

A simple approach

Drupal supports Text Formats which allow you to control how user-contributed content is filtered and formatted, as well as the text editor user interface (WYSIWYGs or toolbars). You can access the configuration for text formats at : admin/config/content/formats.

Most Text Formats include some kind of filtering, for example the 'Plain text' format would take all the HTML in your widget and escape it to make it safe (if you used this in a custom block you would see the code on your web page but the browser would not run it).

By default the Text Format with least filtering is 'Full HTML' usually this will be configured to use a Wysiwyg editor. In theory a user who is trusted to use 'Full HTML' could switch to source mode on the Wysiwyg editor, past in the code for their Twitter widget, place the block appropriately and everthing will work.

The problem with the above approach is that editing the custom block will display the Wysiwyg editor by default, and there is still a minimal amount of filtering applied to clean up HTML etc. that could in theory break your widget. Another issue is that although you have already given a lot of responsibility to a user/role by allowing them to use 'Full HTML' you may want to differentiate that from the permission you give to allow widgets (otherwise they may get all sorts of crazy ideas into their head).

One solution is to create another Text Format with an appropriate name and then ensure that all filters are disabled on it. This format can only be allowed for people you really trust (Me in this case, but I am even wavering a little on that one). Entering the widget code into a custom block should allow you to position it anywhere where blocks can go and provide a nice clean editing experiance. 

Remember what is says in Text Formats though: Improper text format configuration is a security risk!

Shortcomings

  • The positioning of the code you enter is dependant on where you can put blocks, so not any use if you are instructed to put it at the end of the <head> section of the page for example.
  • You may have to style out any styling of the block that is giving your widget a funky border or extra padding etc.