Skip to content

Commit

Permalink
Use temporary rewriting of curly brackets when rendering MD content
Browse files Browse the repository at this point in the history
Fixes #992
  • Loading branch information
bennothommo committed Oct 16, 2023
1 parent 8f7c656 commit c311471
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions modules/cms/classes/Content.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php namespace Cms\Classes;
<?php

use File;
use Markdown;
namespace Cms\Classes;

use Winter\Storm\Support\Facades\File;
use Winter\Storm\Support\Facades\Markdown;

/**
* The CMS content file class.
Expand Down Expand Up @@ -62,12 +64,46 @@ public function parseMarkup()
$result = htmlspecialchars($this->markup);
break;
case 'md':
$result = Markdown::parse($this->markup);
$result = $this->parseMarkdownMarkup($this->markup);
break;
default:
$result = $this->markup;
}

return $result;
}

/**
* Parse Markdown content files.
*
* This method replaces curly variables in the content temporarily while Markdown rendering takes place, to
* circumvent the escaping that Commonmark does on curly brackets in links.
*
* @param string $markup
* @return string
*/
protected function parseMarkdownMarkup(string $markup): string
{
/**
* Replace variables temporarily for Markdown parsing, as the Commonmark library escapes curly brackets in
* links.
* @see https://github.com/wintercms/winter/issues/992
*/
$variables = [];
$markup = preg_replace_callback('/\{([^\n \}]+)\}/', function (array $matches) use (&$variables) {
$signature = hash('sha256', $matches[1]);
if (!array_key_exists($signature, $variables)) {
$variables[$signature] = $matches[1];
}
return ".=VAR={$signature}=.";
}, $markup);

$markup = Markdown::parse($markup);

foreach ($variables as $signature => $variable) {
$markup = str_replace(".=VAR={$signature}=.", "{{$variable}}", $markup);
}

return $markup;
}
}

0 comments on commit c311471

Please sign in to comment.