【Jinja】Includeブロック内で変数を展開する

Goal

  • JinjaのIncludeブロックで指定するファイル名を変数で指定する

Includeブロック内では、Jinjaの構文では変数が展開されず、文字列として認識されてしまう。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        {% include "{{ variable }}" %} <!-- これだと Template not found error となってしまう-->
  </body>
</html>

Environment

  • Jinja 3.1.2

Resolve

Jinja2 2.7.1 以降では、下記で展開可能。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        {% include "%s" % variable %}
        {% include "/files/%s" % variable %}
  </body>
</html>

Jinja2 2.7.1 以前でも、理論上は下記で回避可能。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        {% include "templates/case/"+variable+"/intro.html" %}
        {% include "/files/"+cid %}
  </body>
</html>

Reference

https://stackoverflow.com/questions/12233971/using-include-to-dynamically-point-to-html