PythonテンプレートエンジンJinjaの簡易的なまとめ

はじめに

PythonのテンプレートエンジンJinjaの簡易的なまとめ。

参考:Jinja, Macros, and Packages

変数

Input

{% set number = 100 %}
I want to write Jinja for {{ number }}!

Output

wow! cool!
I want to write Jinja for 100!

コメント

Input

{#
    これはコメント
#}

Output




リスト

Input

{% set my_animals = ['lemur', 'wolf', 'panther', 'tardigrade'] %}

{{ my_animals[0] }}
{{ my_animals[1] }}
{{ my_animals[2] }}
{{ my_animals[3] }}

Output

lemur
wolf
panther
tardigrade

ループ

Input

{% for animal in ['lemur', 'wolf', 'panther', 'tardigrade'] %}
    My favorite animal is the {{ animal }}
{% endfor %}

Output

     My favorite animal is the lemur

    My favorite animal is the wolf

    My favorite animal is the panther

    My favorite animal is the tardigrade

if

Input

{% set temperature = 45 %}

{% if temperature < 65 %}
    Time for a cappucino!
{% else %}
    Time for a cold brew!
{% endif %}

Output

     Time for a cappucino!

辞書

Input

{% set websters_dict = {
    'word': 'data',
    'speech_part': 'noun',
    'definition': 'If you know you know'
} %}
{{ websters_dict['word']}}

Output

data

SQLへの応用例

Input

{% for i in range(5) %}
    select {{i}} as number {% if not loop.last %} union all {% endif %}
{% endfor %}

Output

select 0 as number  union all 

select 1 as number  union all 

select 2 as number  union all 

select 3 as number  union all 

select 4 as number  union all 

select 5 as number

さいごに

生のJinjaを利用するのではなく目的に沿ったラッパーライブラリを使うとよいでしょう。例えばSQLにはdbtの相性が良さそうです。