本文介绍了从字面上将静态文件插入Jinja模板而无需解析它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用include
标记使用Jinja 2.6将文件插入页面.在我开始在文件中使用让人联想到Jinja语法的字符之前,此方法一直很好,这时它意识到无法解析它们并对其进行轰炸.
I'm trying to insert file into a page using Jinja 2.6 using the include
tag. This worked fine until I started using characters in the file that are reminiscent of the Jinja syntax, at which point it realized it couldn't parse them and bombed.
如果要遍历文件并转义所有字符,我该怎么做才能告诉Jinja照原样包含文件?
Short of going though the file and escaping all characters, what can I do to tell Jinja to just include the file as is?
推荐答案
您可以定义一个函数来加载文本文件并将其呈现在模板中:
You can define a function to load the text file and render it in the template:
import jinja2
def include_file(name):
return jinja2.Markup(loader.get_source(env, name)[0])
loader = jinja2.PackageLoader(__name__, 'templates')
env = jinja2.Environment(loader=loader)
env.globals['include_file'] = include_file
def render():
return env.get_template('page.html').render()
if __name__ == '__main__':
print render()
在模板中,这样命名:
{{ include_file('file.txt') }}
这篇关于从字面上将静态文件插入Jinja模板而无需解析它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!