例如:
str = "<b>Hello<b> this string also includes my {{myvariable}} {%if myvariable%} and its true {%endif%}"
我知道|safe
过滤器存在,但它不适用于内联html,仅适用于html。autoescape off
也一样。
您必须决定是否要在Python中执行此格式化并将其传递给模板,还是在模板中。此外,您是否希望对myvariable中的特殊字符进行转义
模板中:
<b>Hello<b> this string also includes my {{myvariable}} {%if myvariable%} and its true {%endif%}"
或避免转义
<b>Hello<b> this string also includes my {{myvariable|safe}} {%if myvariable%} and its true {%endif%}"
在Python中使用转义
annitt = "and its true " if myvariable else ""
safestr = format_html(
"<b>Hello<b> this string also includes my {} {}", myvariable, anitt)
没有逃避
annitt = "and its true " if myvariable else ""
unsafestr = f"<b>Hello<b> this string also includes my {myvariable} {anitt}"
safestr = mark_safe( unsafestr)
传递给模板,其中,{{safestr}}
像这样使用
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)
对于所有需要看到的,这里有一个教程:
首先需要你的字符串:
str = '{{ value.passed }}{% if not value.passed %}. Thats not good, Look here for help <a href="https://{{url}}" target="_blank">Google</a>.{% endif %}'
,然后使用渲染函数和上下文来影响模板:
from django.template import Context, Template
t = Template(str)
dict = {'value':{'passed': False} ,'url': "www.google.com"}
newstr = (t.render(Context(dict)))
最后但并非最不重要的是使用一种方法来执行HTML代码
我现在使用这个方法(感谢@Dad)
from django.utils.safestring import mark_safe
str = mark_safe(newstr)