如何在Jinja的include标签中使用变量作为引入文件的路径?
问题解答
Jinja 原生支持直接传入变量作为 include 标签的文件路径,你期望的效果完全可以实现,仅需要修正你当前示例代码中 include 语句的错误写法即可。
错误原因
你当前写的 {% include "'" Mypath "'" %} 属于多余的引号拼接操作,include 标签接收变量时不需要额外添加包裹引号,变量本身存储的合法路径字符串就可以直接被识别。
正确写法
将 include 语句修改为如下形式即可,运行效果完全等价于 {% include 'Templates/file2.j2' %}:
{% include Mypath %}
补充说明
- 变量存储的路径只要符合你项目模板加载器的路径匹配规则即可,不需要额外做格式转换
- 如果需要兼容路径不存在的场景,可以添加
ignore missing参数避免抛出异常,写法如下:{% include Mypath ignore missing %}
修改后完整示例代码
{% set filepath = ['Templates/file1.j2', 'Templates/file2.j2', 'Templetes/file3.j2'] %} These are the files: {% for list in filepath -%} '{{ list }}' {% endfor %} {% set Mypath = filepath[1] %} This is the path and file to use: '{{ Mypath }}' {% include Mypath %}
内容的提问来源于stack exchange,提问作者CjD
相关产品推荐
相关产品推荐

