从字面上将静态文件插入Jinja模板而无需解析它们

编程入门 行业动态 更新时间:2024-10-28 03:21:00
本文介绍了从字面上将静态文件插入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模板而无需解析它们

本文发布于:2023-11-23 11:04:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621223.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字面   上将   静态   模板   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!