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
CodePudding user response:
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}}
CodePudding user response:
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)