I have a string which is to be displayed in an html file. Certain words (tagged as "spc") in the string need to be displayed in yellow background and larger font.
I was trying to send the string (called tdoc) to the html file using render_to_response
method. I replaced the 'spc' tag in the string with a div tag. Suppose, after replacement, part of the string is we would seldom be prepared to <div id="spcl">examine</div> every
. My django code looks like render_to_response('a.html',{'taggeddoc':tdoc})
In my css, I have following code
#spcl {
background-color: #FFFF00;
font-size:15px;
}
So, I should see the word examine in bold font and yellow background, but I don't see that. When I viewed the source of the rendered html, it has following substring We would seldom be prepared to <div id="spcl">examine</div> every
instead of the original string.
How can I make the word 'examine' and similar words display in the required way?
Use mark_safe
to prevent html escape:
from django.utils.safestring import mark_safe
...
render_to_response('a.html', {'taggeddoc': mark_safe(tdoc)})
Or use safe
filter in template:
{{ taggeddoc|safe }}
Example:
>>> from django.utils.safestring import mark_safe
>>> from django.template import Template, Context
# without mark_safe, safe
>>> print(Template('{{ taggeddoc }}').render(Context({'taggeddoc': '<div>hello</div>'})))
<div>hello</div>
# mark_safe
>>> print(Template('{{ taggeddoc }}').render(Context({'taggeddoc': mark_safe('<div>hello</div>')})))
<div>hello</div>
# safe filter
>>> print(Template('{{ taggeddoc|safe }}').render(Context({'taggeddoc': '<div>hello</div>'})))
<div>hello</div>