Skip to content

markdown_to_html different/incorrect behavior with leading line-break #3685

Description

@Sarke

I thought I was going mad at one point. I've simplified the issue to the following code:

$loader = new \Twig\Loader\ArrayLoader([
    'index' => '{{ text|markdown_to_html }}',
]);
$twig = new \Twig\Environment($loader);
$twig->addExtension(new MarkdownExtension());

$twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
    public function load($class) {
        if (MarkdownRuntime::class === $class) {
            return new MarkdownRuntime(new DefaultMarkdown());
        }
    }
});

$markdown = <<<MD
Paragraph 1

Paragraph 2

1. First

2. Second
MD;

echo $twig->render('index', ['text' => $markdown]);

echo "\n------\n\n";

// only difference is the leading line-break
$markdown = "\n" . $markdown;

echo $twig->render('index', ['text' => $markdown]);

Output

<p>Paragraph 1</p>

<p>Paragraph 2</p>

<ol>
<li><p>First</p></li>
<li><p>Second</p></li>
</ol>

------

<p>Paragraph 1<br />
Paragraph 2<br />
1. First<br />
2. Second</p>

I originally noticed it when I was getting the second (incorrect) results with this, which seems harmless enough.

{% apply markdown_to_html %}

Title

Similar effects with other markdown libraries. Note that passing a leading line-break to the markdown library directly (without Twig) works as expected.

michelf/php-markdown               1.9.1
twig/markdown-extra                v3.3.8
twig/twig                          v3.3.9

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions