9
6

More than 3 years have passed since last update.

【jinja2】for文内で加算した変数が引き継がれない問題の解決策

Last updated at Posted at 2019-12-21

はじめに

<バージョン>
Python: 3.7.4
jinja2: 2.7.2

以下のようなコードがあり、for文内でcntという変数を加算していったとします。

count_test.j2
{%- set cnt = 1 -%}
{%- for i in range(3) -%}
{%- set cnt = cnt + 1 -%}
{{ cnt }}
{% endfor -%}
result : {{ cnt }}

実行結果(失敗例)

結果を見てみると、for文の外には変数に加算した結果が引き継がれていないことがわかります。

出力
2
3
4
result : 1

バージョンによっては、加算されない場合もあるようです。

出力
2
2
2
result : 1

解決策1:リストに格納する

加算した結果をリストに格納すると上手くいきます。
加算した値をappendでリストに足して、加算前の値はpopで削除します。

count_test2.j2
{%- set cnt = [1] -%}
{%- for i in range(3) -%}
{%- set _ = cnt.append(cnt[0] + 1) -%}
{%- set _ = cnt.pop(0) -%}
{{ cnt[0] }}
{% endfor -%}
result : {{ cnt[0] }}

解決策2:namespaceを使う

<2019/12/21:na90ya様より>
jinja2の2.10で導入されたnamespace objectsを利用すると変数が維持されるようです。(参考資料[1])

count_test3.j2
{%- set ns = namespace(cnt=1) -%}
{%- for i in range(3) -%}
{%- set ns.cnt = ns.cnt + 1 -%}
{{ ns.cnt }}
{% endfor -%}
result : {{ ns.cnt }}

実行結果(成功例)

結果を見てみると、for文の外でも変数が加算されたままになっています。

出力
2
3
4
result : 4

参考資料

[1]Template Designer Documentation

9
6
1

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
9
6