您看到的 HTML 只是一个预览,因此将其存储在数据库中并不是一个好主意,因为您在尝试编辑时会遇到问题。存储两个版本(markdown 和 HTML)也不是一个好主意,因为 HTML 只是一种解释,您在编辑和保持两个版本同步时会遇到同样的问题。
所以最好的办法是将markdown存储在数据库中,然后在显示之前将其转换为服务器端。
您可以为此目的使用PHP Markdown。然而,这并不是您在 javascript 端看到的 100% 完美转换,可能需要一些调整。
Stack Exchange network 使用的版本是 C# 实现,应该有你下载的带有 wmd 版本的 python 实现。
我调整的一件事是新行的呈现方式,所以我在 markdown.php 中进行了更改,以从我拥有的版本的第 626 行开始将一些新行转换为 <br>:
var $span_gamut = array(
#
# These are all the transformations that occur *within* block-level
# tags like paragraphs, headers, and list items.
#
# Process character escapes, code spans, and inline HTML
# in one shot.
"parseSpan" => -30,
# Process anchor and image tags. Images must come first,
# because ![foo][f] looks like an anchor.
"doImages" => 10,
"doAnchors" => 20,
# Make links out of things like `<http://example.com/>`
# Must come after doAnchors, because you can use < and >
# delimiters in inline links like [this](<url>).
"doAutoLinks" => 30,
"encodeAmpsAndAngles" => 40,
"doItalicsAndBold" => 50,
"doHardBreaks" => 60,
"doNewLines" => 70,
);
function runSpanGamut($text) {
#
# Run span gamut tranformations.
#
foreach ($this->span_gamut as $method => $priority) {
$text = $this->$method($text);
}
return $text;
}
function doNewLines($text) {
return nl2br($text);
}