skip to Main Content

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 ?)

2

Answers


  1. Chosen as BEST ANSWER

    I updated my filter, following Colin O'Dells answer. This way, it is more robust, and it will allow the usage or creation of more CommonMark extensions in the future.

    # srcTwigCustomTwigExtension.php
    <?php
    
    declare(strict_types=1);
    
    namespace AppTwig;
    
    use LeagueCommonMarkEnvironmentEnvironment;
    use LeagueCommonMarkExtensionCommonMarkCommonMarkCoreExtension;
    use LeagueCommonMarkExtensionConfigurableExtensionInterface;
    use LeagueCommonMarkExtensionInlinesOnlyInlinesOnlyExtension;
    use LeagueCommonMarkMarkdownConverter;
    use TwigExtensionAbstractExtension;
    use TwigMarkup;
    use TwigTwigFilter;
    use WebmozartAssertAssert;
    
    class CustomTwigExtension extends AbstractExtension
    {
        private const CONFIG = [
            'default' => [CommonMarkCoreExtension::class],
            'inline' => [InlinesOnlyExtension::class],
        ];
    
        /**
         * @return TwigFilter[]
         */
        public function getFilters(): array
        {
            return [
                new TwigFilter('custom_markdown', [$this, 'customMarkdown']),
            ];
        }
    
        public function customMarkdown(string $str, string $configName = 'default'): Markup
        {
            $env = new Environment();
            foreach ($this->getExtensions($configName) as $extension) {
                $env->addExtension($extension);
            }
            $converter = new MarkdownConverter($env);
            $html = $converter->convert($str)->getContent();
    
            return new Markup($html, 'UTF-8');
        }
    
        /**
         * @return ConfigurableExtensionInterface[]
         */
        private function getExtensions(string $configName): array
        {
            Assert::keyExists(self::CONFIG, $configName);
    
            $extensions = [];
            foreach (self::CONFIG[$configName] as $extension) {
                $extensions[] = new $extension();
            }
    
            return $extensions;
        }
    }
    

    It is called like this in the templates:

    {{ markdown_content|custom_markdown }} {# to use the default markdown configuration #}
    
    {{ markdown_content|custom_markdown('inline') }} {# to remove all paragraph tags from the result #}
    

  2. 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 LeagueCommonMarkEnvironmentEnvironment;
    use LeagueCommonMarkExtensionInlinesOnlyInlinesOnlyExtension;
    use LeagueCommonMarkMarkdownConverter;
    
    // 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search