Advertising sustains the DA. Ads are hidden for members. Join today

Services

Last updated on
8 March 2021

Dependency Injection

If you need to parse Markdown in other services, inject it as a dependency:

use \Drupal\markdown\MarkdownInterface;

class MyService {

  /**
   * The Markdown service.
   *
   * @var \Drupal\markdown\MarkdownInterface
   */
  protected $markdown;

  /**
   * MyService constructor.
   *
   * @param \Drupal\markdown\MarkdownInterface $markdown
   *   The Markdown service.
   */
  public function __construct(MarkdownInterface $markdown) {
    $this->markdown = $markdown;
  }

  /**
   * MyService renderer.
   */
  public function render(array $items) {
    $build = ['#theme' => 'item_list', '#items' => []];
    foreach ($items as $markdown) {
      $build['#items'][] = $this->markdown->parse($markdown);
    }
    return $build;
  }
}

Trait

If you need to use Markdown in a class where modifying the constructor may prove difficult, use the MarkdownTrait:

use \Drupal\markdown\Traits\MarkdownTrait;

class MyController {

  use MarkdownTrait;

  /**
   * MyService renderer.
   */
  public function render(array $items) {
    $build = ['#theme' => 'item_list', '#items' => []];
    foreach ($items as $markdown) {
      $build['#items'][] = $this->markdown()->parse($markdown);
    }
    return $build;
  }

}

Static

If you need to use Markdown in legacy procedural functions for hooks and alters:

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\markdown\Markdown;

/**
 * Implements hook_help().
 *
 * {@inheritdoc}
 */
function my_module_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.markdown':
      return Markdown::create()->loadFile(__DIR__ . '/README.md');
  }
}

Help improve this page

Page status: No known problems

You can: