How can I use a string in django as html? which includes djangos inline html

For example:

str = "<b>Hello<b> this string also includes my {{myvariable}} {%if myvariable%} and its true {%endif%}"

I know that the |safe filter exists, but that doesn´t work for inline html, only for html. Same here for the autoescape off.

I would be happy if somebody could help me :D

Use it like this

from django.utils.safestring import mark_safe

str = "<b>Hello<b> this string also includes my {{myvariable}} {%if myvariable%} and its true {%endif%}"

str = mark_safe(str)

You have to decidde if you are going to do this formatting in Python and pass it to the template, or in the template. Also, whether you want special characters in myvariable to be escaped, or not.

In a template:

<b>Hello<b> this string also includes my {{myvariable}} {%if myvariable%} and its true {%endif%}"

or to avoid escaping

<b>Hello<b> this string also includes my {{myvariable|safe}} {%if myvariable%} and its true {%endif%}"

In Python with escaping

annitt = "and its true " if myvariable else ""
safestr = format_html( 
    "<b>Hello<b> this string also includes my {} {}", myvariable, anitt)

Without escaping

annitt = "and its true " if myvariable else ""
unsafestr = f"<b>Hello<b> this string also includes my {myvariable} {anitt}"
safestr = mark_safe( unsafestr)

Pass it to the template, and therein, {{safestr}}

For all that need to see that, here is a tutorial:

first you need your string:

str = '{{ value.passed }}{% if not value.passed %}. Thats not good, Look here for help <a href="https://{{url}}" target="_blank">Google</a>.{% endif %}'

then use the render funktion and a context to effect the Template:

from django.template import Context, Template
t = Template(str)
dict = {'value':{'passed': False} ,'url': "www.google.com"}
newstr = (t.render(Context(dict)))

last but not least use a way to execute the html code

I use this methode now (thanks to @Dad)

from django.utils.safestring import mark_safe

str = mark_safe(newstr)
Back to Top