Skip to main content
 首页 » 编程设计

python之使用 bottle framwork 在 tpl 中显示文本文件内容的问题

2025年05月04日10telwanggs

到目前为止,我一直在尝试在模板中显示文本文件的内容,但没有成功。这是 到目前为止我的代码:

@route('/show_article/<filename>') 
def show_article(filename): 
    stat_art=static_file(filename, root="articles") 
 
    return template('show_article', stat_art=stat_art) 

这是我模板中显示文件内容的段落

<p> 
    {{stat_art}} 
</p> 

我知道我可以只返回 static_file() 但我需要设计页面 一些 CSS 和其他东西。

如果我的英语不正确,请提前致谢!

请您参考如下方法:

你误解了 static_file 的作用。

幸运的是,修复很简单:自己读取文件并将其内容传递给模板,如下所示:

@route('/show_article/<filename>') 
def show_article(filename): 
    with open(filename) as f:  # <-- you'll need the correct path here, possibly including "articles" 
        stat_art = f.read() 
 
    return template('show_article', stat_art=stat_art) 

这应该可以解决问题。

[顺便说一句,第一个问题很好!]