简体   繁体   中英

Rendering html in template from a received variable - Django template rendering

I currently have a variable that contains a string HTML which resembles this

myvar = "<p style="-qt-block-indent: 0; text-indent: 0px; margin: 18px 0px 12px 0px;"><span style="font-size: xx-large; font-weight: 600; color: #5e9ca0;"> ..."

I am passing this string to my template like so

      return render(request, "rendered.html", {
            'result': myvar,
        })

In the template I am simply doing

{{myvar}}

This shows me on the screen the exact html as text but not rendered. When I investigated the source this is what i got

 &lt;p style=&quot;-qt-block-indent: 0; text-indent: 0px; margin: 18px 0px 12px 0px;&quot;&gt;&lt;span style ...

while I was suppose to get

<p style="-qt-block-indent: 0; text-indent: 0px; margin: 18px 0px 12px 0px;"><span style="font-size: xx-large; font-weight: 600; color: #5e9ca0;"> 

Any solution on how I can fix this issue ?

What is happening ?

Django by default is escaping your html thinking that it might be harmful hence escaping it by default.

Since you need to NOT escape it. Wrap your variable within autoescape filter

    {% autoescape off %}
    {{ myvar}}
    {% endautoescape %}

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