Drupal 8 - simple BB code pre-processing

As part of converting my site from Drupal 7 to Drupal 8, I ran into an issue with the core CKEditor not supporting <code> tags. The tags display fine after the intial node save, but get filtered out on subsequent node edits, regardless of the "Limit allowed HTML tags" option in the text format settings. Google turned up various discussions dating back to Drupal 6 days with this very issue, with finger pointing between Drupal, CK Editor module, and the CK Editor library itself. 

With no concrete solution in sight and not wishing to spend half a day debugging core & CK Editor, I used hook_node_view_alter() to add support for the [code] BB tag:

/** * Implements hook_node_view_alter(). */ function hook_node_view_alter(&$build, \Drupal\Core\Entity\EntityInterface $node, \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display) { if (isset($build['body'][0]['#markup'])) { $build['body'][0]['#markup'] = preg_replace('/\[(\/{0,1})code\]/', '<$1code>', $build['body'][0]['#markup']); } }

Note that this will not handle nested [code] tags.

comments powered by Disqus