Question: How to insert a node during DocumentParsedEvent #633
-
QuestionHey there 👋 I'm really diving into the guts of this library and it's fantastic. Thanks for making it! I'm having a hard time figuring out how to insert a new e.g. html block inside of the DocumentParsedEvent. I have successfully registered the event and am able to generate the block, but the I see that
I've looked at the TOC generator extension because it inserts brand new nodes, but it looks like it uses a custom block with corresponding renderer? I just want to insert some plain 'ol HTML. In my example I'm inserting a heading, but that's just because I'm trying to get anything to show up. Thanks for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Thanks for the kind feedback! Inserting new nodes during (In 2.x we're removing all node methods and properties that are solely used for parsing, as it incorrectly mixes two responsibilities into one class that should know absolutely nothing about how it was parsed.) For example, instead of this: $block = new Heading(1, 'Test!'); You'll actually need to manually create the child $block = new Heading(1);
$block->appendChild(new Text('Test!')); Everything else in your example should work. I hope that helps! |
Beta Was this translation helpful? Give feedback.
-
@colinodell excellent, this is very helpful and pointed me in the right direction. Thank you! I ended up making my own block: use League\CommonMark\Block\Element\HtmlBlock;
class ArbitraryHtmlBlock extends HtmlBlock
{
public function __construct($contents)
{
if (is_array($contents)) {
$contents = implode("\n", $contents);
}
$this->finalStringContents = $contents;
}
} which I can just pass HTML to: $node->insertAfter(new ArbitraryHtmlBlock($html)); Thanks for the help in getting it sorted! |
Beta Was this translation helpful? Give feedback.
-
Ah okay, that works! I also want to offer two tips for you and anyone else who might stumble on this issue in the future:
|
Beta Was this translation helpful? Give feedback.
Thanks for the kind feedback!
Inserting new nodes during
DocumentParsedEvent
is a little weird due to inconsistencies with how nodes and parsing is implemented in 1.x. In a nutshell, you can't rely onfinalize()
,finalStringContents
, or any block constructor parameter that accepts inner contents. These only exist for the sake of the previous parsing step. During parsing, the engine will use that information to construct all of the child elements. But once parsing is completed the engine will no longer look at those properties or do anything with them.(In 2.x we're removing all node methods and properties that are solely used for parsing, as it incorrectly mixes two responsibilities into …