備忘録

【Jinja2】テンプレートにパラメータを渡す

前提

Python: 3.12
Jinja2: 3.1.3

テンプレートにパラメータを渡す

tpl = env.get_template('template.tpl')
params = {
  'navigation': [
  {
    'href': 'https://example.com/',
    'text': 'Home'
  },
  {
    'href': 'https://example.com/about/',
    'text': 'About'
  }
  ]
}
tpl.render(params)

上記のようなパラメータを渡した場合、テンプレートでは以下のように使用できる。

template.tpl
<ul>
{% for item in navigation  %}
  <li><a href="{{ item.href }}">{{ item.text }}</a></li>
{% endfor %}
</ul>

includeしたファイルに渡す

{% with %} {% endwith %}ブロックを使用してパラメータを渡すことができる。

template.tpl
<ul>
{% for item in navigation  %}
  {% with item = item %}
  {% include 'partials/link.tpl' %}
  {% endwith %}
{% endfor %}
</ul>

partials/link.tpl
<li><a href="{{ item.href }}">{{ item.text }}</a></li>

関連記事

  • 【Jinja2】PythonのテンプレートエンジンJinja2を使う
    前提 Python: 3.12 Jinja2: 3.1.3 Install pip install Jinja2 Sample from jinja2 import Environment, FileSystemLoader loader = FileSystemLoader(template_dir, encoding='utf-8') env = Environment(Loader=loader, autoescape=False) tpl = env.get_template(template_name) params = { 'title': 'Example Page Title' } with open(path, mode='w', encoding='utf-8') as f: f.write(tpl.render(params)) 変数 テンプレート内での使用 <h1>{{ title }}</h1> for文の中で使用できる
  • 【Python】Pythonの開発環境構築
    前提 Windows インストール 以下のサイトからインストーラーをダウンロードしてインストールするか、scoopを使用してインストールする。 https://www.python.org/downloads/windows/ scoop install python IDE(