Reputation: 61
I am writing a flask powered blog and I want to present my comments saved in XML format to the browser, so I opened the XML file and I read from it.
from xml.etree.ElementTree import parse
def blue():
with open('blogcomment.xml') as file:
doc = parse(file)
return '\n'.join("""
<div class="card">
<span></span>
<div class="content">
<p class="date">%s</p>
<h3></h3>
<p class="desc">%s</p>
</div>
</div>
"""%(item.findtext('date'), item.findtext('body')) for item in doc.iterfind('entries/entry'))
Then I called blue
@sqldb.route('/dbresult')
def dbresult():
f = blue()
return f
#Output:
11/14/2007
in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.
11/18/2007
I got the new cube I ordered. It’s a real pearl.
Which is what I wanted but I want it to be in a particular section of my blog, so I created
<!doctype html>
<html>
<head>
</head>
<body>
{{f}}
</body>
</html>
And changed my route to
@sqldb.route('/dbresult')
def dbresult():
f = blue()
return render_template('dbresult.html', f=f)
when I ran the code It Outputted
<div class="card"> <span></span> <div class="content"> <p class="date">11/14/2007</p> <h3></h3> <p
class="desc">in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.</p> </div> </div> <div
class="card"> <span></span> <div class="content"> <p class="date">11/18/2007</p> <h3></h3> <p
class="desc">Got the new cube I ordered. It’s a real pearl.</p> </div> </div>
on the browser as the browser did not interpret the HTML, is it from Jinja2 or what did I do wrong I need help.
blogcomment.xml
<?xml version="1.0"?>
<blog>
<entries>
<entry>
<date>11/14/2007</date>
<name>Jeff</name>
<body>in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.</body>
</entry>
<entry>
<date>11/18/2007</date>
<name>Petter</name>
<body>Got the new cube I ordered. It’s a real pearl.</body>
</entry>
</entries>
</blog>
Upvotes: 1
Views: 140
Reputation: 10517
Flask's default configuration includes autoescaping for .html
templates. Therefore when you put {{ f }}
into the template the f
variable is treated as an unsafe variable and any 'dangerous' character (e.g. <
or >
) will be escaped (converted to a HTML entity).
To prevent this behavior you can use the safe template filter, which marks the variable as safe so it will not be escaped:
<!doctype html>
<html>
<head>
</head>
<body>
{{ f | safe }}
</body>
</html>
Make sure that f
does not contain any malicious code.
A better approach would be that in your blue
method you just prepare the data to render (e.g. make a list of dicts from the data) and then you render the comments in a template file using the built in for
control statement.
Upvotes: 1