PHP code example of markdown-office / commonmark-generic-directives

1. Go to this page and download the library: Download markdown-office/commonmark-generic-directives library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

markdown-office / commonmark-generic-directives example snippets


use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\MarkdownConverter;
use MarkdownOffice\CommonMark\Directive\GenericDirectiveExtension;

$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addExtension(new GenericDirectiveExtension());

$html = (new MarkdownConverter($environment))->convert($markdown);

use League\CommonMark\Node\Node;
use League\CommonMark\Renderer\ChildNodeRendererInterface;
use League\CommonMark\Renderer\NodeRendererInterface;
use MarkdownOffice\CommonMark\Directive\Node\DirectiveBlock;

final class CalloutRenderer implements NodeRendererInterface
{
    public function render(Node $node, ChildNodeRendererInterface $childRenderer): string
    {
        \assert($node instanceof DirectiveBlock);

        $type = $node->getAttributes()->getString('type', 'note');

        return sprintf(
            '<aside class="callout callout--%s">%s</aside>',
            htmlspecialchars($type, ENT_QUOTES),
            $childRenderer->renderNodes($node->children())
        );
    }
}

$environment->addRenderer(DirectiveBlock::class, new CalloutRenderer(), 10);

$attributes = $node->getAttributes();

$attributes->getString('title', 'Untitled');   // string|null
$attributes->getInt('width', 400);             // int|null
$attributes->getFloat('ratio');                // float|null
$attributes->getBool('open', false);           // bool
$attributes->getList('tags');                  // list<string>
$attributes->has('title');                     // bool
$attributes->toArray();                        // array<string, string|true>

use MarkdownOffice\CommonMark\Directive\Directive\DirectiveRegistry;

$environment->addExtension(new GenericDirectiveExtension(
    new DirectiveRegistry(['col', 'callout', 'badge:text'])
));

// :::columns → UnknownDirective:
//   Unknown container directive "columns". Registered: badge:text, callout, col.

$node->getName();        // 'callout', or null for a container written without one
$node->getType();        // DirectiveType::Container | Leaf | Text
$node->getLabel();       // 'Chart', or null when there is none
$node->getAttributes();  // DirectiveAttributes
$node->isContainer();    // bool
(string) $node;          // back to source form