Easy Solution to wrap html-elements around custom parsed md/cm-elements? #635
-
Hello, i use at the moment this lib with custom parsing commonmark into html with the CommonMarkConverter. Now i have a problem that i simple want the How can i tell the lib that i want some html-blocks around the standard-parsing? Or should i make an new commonmark-tag? Can anybody help me with a code-example? That will be nice. thx |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
You could create a custom block renderer that replaces the built-in heading renderer. For example, you could do something like this: <?php
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Element\Heading;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\Block\Renderer\HeadingRenderer;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\HtmlElement;
final class MyCustomHeadingRenderer implements BlockRendererInterface
{
private BlockRendererInterface $coreHeadingRenderer;
public function __construct()
{
$this->coreHeadingRenderer = new HeadingRenderer();
}
/**
* @param Heading $block
* @param ElementRendererInterface $htmlRenderer
* @param bool $inTightList
*
* @return string
*/
public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false)
{
return '<heading>' . $this->coreHeadingRenderer->render($block, $htmlRenderer, $inTightLight) . '</heading'>;
}
} And then hook that up to the library like this: <?php
use League\CommonMark\Block\Element\Heading;
use League\CommonMark\Environment;
$environment = Environment::createCommonMarkEnvironment();
$myRenderer = new MyCustomHeadingRenderer();
$environment->addBlockRenderer(Heading::class, $myRenderer, 10); I have not tested that code but I think it should work (or at least get you 90% of the way there) |
Beta Was this translation helpful? Give feedback.
-
Thx for the code. |
Beta Was this translation helpful? Give feedback.
-
The code functioned without error. I have a little new queston:
What must i do that the CommonMarkConverter use the new Block-Rendering. At the moment nothing happended when is use this with Commonmarkconverter? thx |
Beta Was this translation helpful? Give feedback.
-
You need to pass the $converter = new CommonMarkConverter([], $environment); |
Beta Was this translation helpful? Give feedback.
-
it works, great thx |
Beta Was this translation helpful? Give feedback.
-
Oh, its only the problem that he put "headings" about every <h*> blocks, give it chance that he only put "headings" around <h*>-blocks that are only in the start of the commonmark?
|
Beta Was this translation helpful? Give feedback.
You could create a custom block renderer that replaces the built-in heading renderer.
For example, you could do something like this: