从Markdown文件渲染静态图像

时间:2020-05-12 02:41:30

标签: python html django markdown django-staticfiles

我很难用Django渲染markdown文件,特别是markdown文件中引用的静态文件。将markdown文件转换为html并将其注入模板后,我无法显示图像。我已尝试将正则表达式在降价转换为html后用适当的静态调用替换src调用,但是它不起作用。

有没有一种特定的方法可以完成?

下面是一个测试.md文件,提供了三种尝试加载图像的方法(markdown和html,然后将其重新替换为regrex,并在md文件中进行了硬编码的静态调用)。所有这些都不起作用。该图像的确显示了静态调用是否在模板中,因此这不是找不到图像文件的问题。

似乎没有进行静态调用。在浏览器中,以下输出,

<img src="{% static 'Images/django_reinhardt.jpg' %}" alt="Django" title="Django" width="500">

这意味着未解析静态调用。

代码

转换用于注入的md文件的视图是:

class MdPageView(TemplateView):
    md_file = "test.md"
    template_name = 'md_viewer/md_base.html'

    def get_context_data(self, **kwargs):

        f = open(os.path.join(os.path.join(settings.BASE_DIR,'markdown'), self.md_file))
        file_content = f.read()
        f.close()

        md = markdown.Markdown(extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite'
        ])
        body = md.convert(file_content)

        ## Convert html image to django static file call

        pattern = r"""src=\"\.\.\/(\w+\/\w*\_\w*.jpg)\""""
        static_replace = r""" src="{% static '\1' %}" """
        body = re.sub(pattern, static_replace, body)

        context = super().get_context_data(**kwargs)
        context['body'] = body

        return context

使用test.md

## This is a markdown test

* This
* is
* a
* list
* ..

$$
a^2 + b^2 = c^2
$$

![Django](../Images/django_reinhardt.jpg "Django")
<img src="../Images/django_reinhardt.jpg" alt="Django" title="Django" width="500" />
<img src="{% static "Images/django_reinhardt.jpg" %}" alt="Django" title="Django" width="500" />

和模板

<!DOCTYPE html>
{% load mathjax %}
{% load static %}
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>MD Viewer</title>
        {% mathjax_scripts %}
    </head>
    <body>
        <div class="container">
            {{ body|safe }}
        </div>
        <!-- The below image renders correctly -->
        <img src="{% static "Images/django_reinhardt.jpg" %}" alt="Django" title="Django" width="500" />


    </body>
</html>

0 个答案:

没有答案
相关问题