Colorfield logo

Drupalicious

Published on

Reuse readme.md in hook_help() with Parsedown

Authors
Parsedown logo

Here is a pretty simple way to maintain the hook_help() of a Drupal project, straight from the readme file.

Markdown is preferred here to .txt so it can be reused on a GitHub, GitLab, ... repository as well.
The downsides of this approach are that we are losing several capabilities like:

  • the Drupal translation and routing system
  • conditional help, e.g. when another related module is installed

Anyway, in most cases, it can be used as a good fallback.

Require the Parsedown library in your composer.json

"require": {
  "erusev/parsedown": "^2.0"
}

Create the README.md file at the root directory of the module.

Then, in the hook_help()

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Component\Utility\Xss;

/**
 * Implements hook_help().
 */
function my_module_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.my_module':
      $parsedown = new Parsedown();
      $readme = file_get_contents(drupal_get_path('module', 'my_module') . '/README.md');
      // Stay permissive here, with filterAdmin.
      $output = Xss::filterAdmin($parsedown->parse($readme));
      return $output;
  }
}

Resources