Markdown模板无法正确呈现HTML

时间:2019-05-22 15:41:15

标签: django markdown django-template-filters

我在Django网站中创建了Markdown过滤器。我已经使用了库markdown2。

尽管HTML可以呈现,但不能完全呈现。 代码和语法突出显示,URL和列表显示不正确。

templatetags文件夹

文件名:ttags.py

from django.template import Library
import markdown2

register = Library()

@register.filter('markdown_to_html')
def markdown_to_html(markdown_text):
    htmlversion=markdown2.markdown(markdown_text)
    return htmlversion

模板文件

{% extends "layout.html" %}
{% load ttags %}
{% load static from staticfiles %}

{% block content %}

<div class="content">
{{ step.description | markdown_to_html | safe }}
</div>

{% endblock %}

提供的要呈现的文本如下

##### Usage of Variables

```python
name = "David"
age = 10
```

In the above example name and age are variables that store Text and Numbers respectively.

> Always remember to use Variables in your programs to store information.

渲染输出的HTML代码如下

<h5>Usage of Variables</h5>

<p><code>python
name = "David"
age = 10
</code></p>

<p>In the above example name and age are variables that store Text and Numbers respectively.</p>

<blockquote>
  <p>Always remember to use Variables in your programs to store information.</p>
</blockquote>

代码语法不会两行显示

1 个答案:

答案 0 :(得分:0)

您需要启用fenced code blocks扩展名,这不是标准的Markdown功能。在您的过滤器定义中执行以下操作:

htmlversion = markdown2.markdown(markdown_text, extras=['fenced-code-blocks'])

请注意,已将extras关键字参数传递给markdown2.markdown。如果您希望语法突出显示也能正常工作,则需要安装pygments和相关CSS文件的副本以定义突出显示样式。

我没有经验,也从未使用过Markdown2库。那么,如何确定这是正确的呢?请注意,受防护的代码块:

```python
name = "David"
age = 10
```

正在渲染到:

<p><code>python
name = "David"
age = 10
</code></p>

受防护的代码块的所有内容(包括语言标识符)都包装在一个内联代码范围(<p><code>)中,而不是一个代码块(<pre><code>)中。这表明Markdown解析器将反引号解释为code span,而不是代码块。由于受防护的代码块不是原始Markdown rules的一部分,因此我们只能假定解析器像大多数其他默认情况下不支持受防护的代码块。实际上,对documentation的快速检查表明,受防护的代码块需要通过扩展名启用才能正常工作。

相关问题