0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?