Skip to main content
 首页 » 编程设计

python之Bottle python 渲染变量作为文本而不是 html

2025年05月04日15del

我在使用 bottle python 时遇到问题,我有以下代码

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 

返回以下列表

['<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>'] 

它又被送入以下 bottlepy 路线:

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

它被输入到 blogroll.tpl 模板中:

<!DOCTYPE html> 
<div> 
 
<p><b>Blog Roll</b></p> 
 
%for postlist in postlist: 
    <li> {{ postlist }} 
%end 
 
</div> 

我的问题是,当我在浏览器中呈现模板时,它会将模板中的 poSTList 变量转换为纯文本而不是 html(列表中写的是什么),但是如果我将 bottle 代码更改为这样读取(绕过模板)它将 poSTList 变量呈现为 html 但不在模板内部,这使得代码无用:

@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 

有人知道为什么会这样吗?

请您参考如下方法:

HTML 特殊字符自动转义以防止 XSS 攻击。

在模板语句的开头使用感叹号表示您确实想要包含 HTML:

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

参见 documentation on inline statements .