Search code examples
phphtmltwigmarkdown

Remove <p> tags from Twig's markdown_to_html()


I'm using Twig's markdown_to_html filter, and it works very well.

However, in some use cases, I'd want it to generate HTML, but without the paragraph tags.

For instance, from this Markdown content:

Hello, this is **some Markdown**

I want the exported HTML to be:

Hello, this is <strong>some Markdown</strong>

But the result is currently:

<p>Hello, this is <strong>some Markdown</strong></p>

I looked into the filter's source and didn't se any option to do so.

Is there a way to do this, or should I create my own Twig filter?

I'd prefer to avoid the striptags filter if possible, because I don't want to list all the tags I'll allow (unless there is a reverse striptags where you can specify the tags you want removed ?)


Solution

  • It looks like you're using league/commonmark which has an "Inlines Only" extension for this exact purpose! It will avoid outputting block-level elements like paragraphs, headers, etc. - only things like emphasis and links would be rendered as HTML.

    To use it, construct your Markdown converter like this:

    <?php
    
    use League\CommonMark\Environment\Environment;
    use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension;
    use League\CommonMark\MarkdownConverter;
    
    // Define your configuration, if needed
    $config = [];
    
    // Create a new, empty environment
    $environment = new Environment($config);
    
    // Add this extension
    $environment->addExtension(new InlinesOnlyExtension());
    
    // Instantiate the converter engine and start converting some Markdown!
    $converter = new MarkdownConverter($environment);
    echo $converter->convert('Hello, this is **some Markdown**');
    

    This will be more reliable than parsing HTML with regular expressions.

    (I'm the maintainer of league/commonmark and would be happy to answer any follow-up questions you might have in the comments)