Flask/Jinja2模板中如何使用变量路径引入文件?
Flask模板动态引入文件的解决方法
你遇到的问题是Jinja2模板引擎不会解析include标签字符串里嵌套的{{ }}变量语法,所以{% include "posts/{{post}}" %}会被当作字面量路径,而非替换post变量后的实际路径。
可行的解决方法有两种:
- 使用Jinja2的字符串连接符
~拼接路径:{% include 'posts/' ~ post %} - 使用字符串格式化语法:
{% include 'posts/{0}'.format(post) %}
注意:确保模板根目录下存在posts子目录,且该目录下有与post变量值匹配的模板文件(比如post值为5时,要有posts/5或posts/5.html,具体取决于你的模板配置)。
内容的提问来源于stack exchange,提问作者ProbablyIdiot
相关产品推荐
相关产品推荐

