简体   繁体   中英

Why are my converted Markdown HTML tags returned as text?

A function in my views.py file converts Markdown files and returns the HTML to another function which is used to show the current entry ( entry() ). In entry() , I have a dictionary that is gives a HTML template access to the converted content. However, when the tags like <h1> and <p> are shown on the page instead of being hidden.

So,

<h1>CSS</h1> <p>CSS is a language that can be used to add style to an <a href="/wiki/HTML">HTML</a> page.</p>

is shown instead of

CSS

CSS is a language that can be used to add style to an HTML page.

--

How do I get rid of the tags on the page and have them actually be used in the HTML file?

entry.html:

{% block body %}
<div class="entry-container">
    <div class="left">
        {{ entry }}
    </div>
    <div class="right">
        <a href="{% url 'edit' %}" class="edit-btn">
            <button class="edit">EDIT</button>
        </a>
    </div>
</div>
{% endblock %}

views.py:

import markdown
from . import util

def entry(request, name):
    entry = util.get_entry(name)
    converted = convert(entry)
    if util.get_entry(name) is not None:
        context = {
            'entry': converted,
            'name': name
        }
        global current_entry
        current_entry = name
        return render(request, 'encyclopedia/entry.html', context)
    else:
        return render(request, "encyclopedia/404.html")

def convert(entry):
    return markdown.markdown(entry)

urls.py:

path('<str:name>', views.entry, name='entry'),

util.py:

def get_entry(title):
    """
    Retrieves an encyclopedia entry by its title. If no such
    entry exists, the function returns None.
    """
    try:
        f = default_storage.open(f"entries/{title}.md")
        return f.read().decode("utf-8")
    except FileNotFoundError:
        return None

Django applies a filter for HTML tags in varibles. If you want the unfiltered output you have to apply the filter safe :

{{ entry | safe }}

Django will be auto-escaping the converted HTML that you pass to the template and won't render any HTML tags. To stop this you can use the safe templatetag:

{{ entry|safe }}

https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#safe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM