Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bottle python rendering variable as text and not html

Tags:

python

bottle

I'm having an issues with bottle python where I have the following code

import glob
import os
from bottle import run, route, error, template
from Find_Posts import hyperlink_postnames

currentdir = os.getcwd()

def hyperlink_postnames():
    hyperlink_filelist = []
    os.chdir(currentdir + "\\Blog_Posts\\")

    for files in glob.glob("*.txt"):
        hyperlink_filelist.append('<a href = "/blog/' + files + '"' + '>' + str(os.path.splitext(files)[0]) + '</a>')
    return  hyperlink_filelist

which returns the following list

['<a href = "/blog/post1.txt">post1</a>', '<a href = "/blog/post2.txt">post2</a>', '<a href = "/blog/post3.txt">post3</a>', '<a href = "/blog/post4.txt">post4</a>', '<a href = "/blog/post5.txt">post5</a>', '<a href = "/blog/post6.txt">post6</a>']

which is in turn fed to the following bottlepy route:

@route('/blog/')
def postnames():
    postlist = hyperlink_postnames()
    tpl_out = template('blogroll', postlist = postlist)
    return  tpl_out

which is fed into the blogroll.tpl template:

<!DOCTYPE html>
<div>

<p><b>Blog Roll</b></p>

%for postlist in postlist:
    <li> {{ postlist }}
%end

</div>

my problem is when I render the template in the browser it turns the postlist variable in the template into plain text and not html (which is what's written inside the list), However if I change the bottle code to read like this (bypassing the template) it renders the postlist variable as html but not inside the template which makes the code useless:

@route('/blog/')
def postnames():
    postlist = hyperlink_postnames()
    tpl_out = template('blogroll', postlist = postlist)
    return  postlist #return the variable directly bypassing the template renders the list as html

does anyone have any ideas as to why this happening?

like image 411
Robert Lear Avatar asked Mar 12 '26 00:03

Robert Lear


1 Answers

HTML special characters are escaped automatically to prevent XSS attacks.

Use an exclamation mark at the start of your template statement to indicate that you really want to include HTML:

%for postlist in postlist:
    <li> {{ !postlist }}
%end

See the documentation on inline statements.

like image 89
Martijn Pieters Avatar answered Mar 15 '26 13:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!