How to create custom block parsing #822
Unanswered
shoaibsharif
asked this question in
Q&A
Replies: 1 comment 1 reply
-
|
Version 2.3 (not yet released) will have an EmbedExtension with a very simple syntax: Just place the link on its own line:
https://codepen.io/shoaibsharif/pen/jOBvbOj
^ Like that2.3.0 probably won't be released for a few weeks, so if you need this sooner (or would like to use the syntax you proposed) then you'll want to implement this as a custom block parser that looks for final class EmbedParser extends AbstractBlockContinueParser
{
/** @psalm-readonly */
private Embed $block;
public function __construct(string $url)
{
$this->block = new Embed($url);
}
public function getBlock(): Embed
{
return $this->block;
}
public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue
{
return BlockContinue::none();
}
public static function blockStartParser(): BlockStartParserInterface
{
return new class () implements BlockStartParserInterface {
/** @psalm-readonly-allow-private-mutation */
private ConfigurationInterface $config;
public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart
{
if ($cursor->isIndented()) {
return BlockStart::none();
}
$cursor->advanceToNextNonSpaceOrTab();
// The line must start with '{% embed'
if ($cursor->match('/^{% +embed +/') === null) {
return BlockStart::none();
}
// There must be an absolute URL next
if (($url = LinkParserHelper::parseLinkDestination($cursor)) === null) {
return BlockStart::none();
}
// The rest of the line must contain whitespace then '%}'
$cursor->advanceToNextNonSpaceOrTab();
if ($cursor->match('/^%} *$/') === null) {
return BlockStart::none();
}
return BlockStart::of(new EmbedParser($url))->at($cursor);
}
};
}
}(This example combines the block start parser and block continue parser into one. You can use separate classes if you prefer.) I recommend looking at these classes for inspiration:
|
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I would like to know how I create an embed using custom notation. i.e. in dev.to markdown editor if we write:
{% embed https://codepen.io/shoaibsharif/pen/jOBvbOj %}It will spit an iframe. I would like to know how I can achieve that in commonmark. I tried to look at the documentation but unfortunately it didn't help me much.
Beta Was this translation helpful? Give feedback.
All reactions