将python渲染变量设置为文本而不是htm

2024-10-01 09:18:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个瓶子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

返回以下列表

^{pr2}$

它又被喂入以下的瓶装路线:

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

它被输入到博客卷.tpl模板:

<!DOCTYPE html>
<div>

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

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

</div>

我的问题是,当我在浏览器中呈现模板时,它会将模板中的postlist变量转换为纯文本而不是html(这是在列表中写入的内容),但是,如果我将瓶子代码改为这样(绕过模板),它将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

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


Tags: 代码import模板returnosdefhtmltemplate
1条回答
网友
1楼 · 发布于 2024-10-01 09:18:58

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

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

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

参见documentation on inline statements。在

相关问题 更多 >