Avoid wrapping single paragraphs in p tags? #812
-
I would like to use Laravel’s Most of these snippets are very short – just a few words or a single sentence – but some are longer, consisting of several paragraphs. In pretty much all cases where the snippet has no paragraph breaks, I would like to get back a converted string that’s not wrapped in So for example, I would like to for these snippets:
– to return this HTML:
I’ve searched through the documentation, particularly of course the configuration part, but I can’t find any mention of a setting or function that would provide this kind of functionality. It’s sort of like inline parsing, except that if the snippet explicitly contains block-level markdown (headers, paragraphs), those should be included. Is it possible to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey there! There's no built-in functionality to enable that behavior. You could probably accomplish this with by decorating the built-in final class AvoidParagraphTagsIfOnlyParagraphRenderer implements NodeRendererInterface
{
private ParagraphRenderer $normalRenderer;
public function __construct(ParagraphRenderer $normalRenderer)
{
$this->normalRenderer = $normalRenderer;
}
public function render(Node $node, ChildNodeRendererInterface $childRenderer): string
{
// Is this paragraph the only block in the document?
if ($node->parent() instanceof Document && $node->previous() === null && $node->next() === null) {
// Yes - so let's render it's children without the usual wrapping <p> tags
return $childRenderer->renderNodes($node->children()) . $childRenderer->getBlockSeparator();
}
// Otherwise, render as usual
return $this->normalRenderer->render($node, $childRenderer);
}
} You can then hook it up to your $environment->addRenderer(Paragraph::class, new AvoidParagraphTagsIfOnlyParagraphRenderer(new ParagraphRenderer())); I haven't actually tested that code but it should work :) |
Beta Was this translation helpful? Give feedback.
Hey there! There's no built-in functionality to enable that behavior. You could probably accomplish this with by decorating the built-in
ParagraphRenderer
with one that immediately returns just the child inlines if it's the only paragraph. Something like this (untested):