【问题标题】:Is there a way to add actual HTML to a template from strings containing HTML markup in Django?有没有办法从 Django 中包含 HTML 标记的字符串将实际的 HTML 添加到模板中?
【发布时间】:2021-07-26 11:48:57
【问题描述】:

所以,我想将包含 HTML 标签的字符串从 Markdown 文件转换为实际的 HTML。然后通过 Django 将 HTML 插入到模板中(这是我第一次使用 Django)。

我当前的输出是什么样的:

我希望屏幕截图中显示的 HTML 像普通 HTML 一样执行,而不是纯文本。

来自我的 views.py 文件的代码:

from django.http.response import HttpResponse
from django.shortcuts import render
from markdown2 import Markdown, markdown
import random
from . import util
import html.parser

# index output
def index(request):
    return render(request, "encyclopedia/index.html", {
        "entries": util.list_entries()
    })

# function to render wiki entries
def page_render(request, title):
    entry = util.get_entry(title)
    if entry != None:
        markdowner = Markdown()
        content = markdowner.convert(entry)
        return render(request, "encyclopedia/display.html", {
        "title": title,
        "content": content
    })
    else:
        return render(request, "encyclopedia/error.html")

来自我的 HTML 模板的代码:

{% extends "encyclopedia/layout.html" %}

{% block title %} 

{{ title }} 

{% endblock %}

{% block body %}
    {{ content }}
{% endblock %}

提前感谢您的帮助!

亲切的问候
PrimeBeat

【问题讨论】:

标签: python html django dom


【解决方案1】:

您可以使用安全标签。

插入这样的内容:{{ content|safe }}

【讨论】:

【解决方案2】:

如果您不希望 HTML 被转义,请查看安全过滤器和 autoescape 标签:

安全:

{{ myhtml |safe }}

自动转义:

{% autoescape off %}
    {{ myhtml }}
{% endautoescape %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 2021-07-08
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2019-12-05
    • 2018-12-14
    相关资源
    最近更新 更多