Reuse readme.md in hook_help() with Parsedown

Submitted by christophe on Sat, 02/03/2019 - 14:56
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

 

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.