1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

jinja2についてまとめてみました。

Posted at

はじめに

jinja2に関しての備忘録。

🦁結論🦁

テンプレートにデータを埋め込むことができるライブラリ。
htmlを自動生成したりできる。

押さえておくべき点

  • 変数埋め込み:テンプレート内で{{ 変数 }}という形式でPythonの変数を埋め込むことができる。
  • 条件分岐:{% if 条件 %}…{% endif %}という形式で条件分岐ができる。
  • ループ:{% for アイテム in リスト %}…{% endfor %}という形式でループ処理ができる。
  • フィルタ:{{ 変数|フィルタ }}という形式で変数に対して特定の処理を行うことができる。

利用シーン

  • ウェブサイトの動的なページ生成:ウェブアプリケーションで、ユーザーごとに違う内容のページを生成する。
  • メールテンプレートの生成:ユーザー名や特定の情報を含むカスタマイズされたメールを送る。
  • レポートの自動生成:データに基づいて自動的にレポートを作成する。
  • 設定ファイルの生成:多くの設定項目を持つ設定ファイルを自動で作成する。
  • ドキュメントの生成:大量のテキストデータをテンプレートに基づいて自動生成する。

注意点

  • 互換性:Jinja2はPythonのバージョンや他のライブラリと互換性があるか確認する必要がある。
  • 範囲選択内でループ処理した場合には、追記されていく。
  • ディレクトリの選択はパスではなくメソッドを使う。

Jinja2の主な機能

テンプレートの書き方

追記したい部分に
{{ title }}を記載

ループ処理するスタート箇所に
{% for item in items %}を記載

ループ処理終了する箇所に
{% endfor %}を記載

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ heading }}</h1>
    <ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
</body>
</html>

Python 使用例

from jinja2 import Environment, FileSystemLoader

# テンプレートファイルが置かれているディレクトリを指定
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

# テンプレートファイルの読み込み
template = env.get_template('template.html')

# テンプレートに埋め込むデータ
data = {
    'title': 'Jinja2の紹介',
    'heading': 'Jinja2でHTMLを作成しよう',
    'items': ['りんご', 'みかん', 'バナナ']
}

# テンプレートをレンダリング(データを埋め込んでHTMLを生成)
output = template.render(data)

# 生成されたHTMLをファイルに保存
with open('output.html', 'w', encoding='utf-8') as f:
    f.write(output)

まとめ✍️

テキストを動的に扱う際にはjinja2の利用頻度は高そう。
扱いもしやすいのでこれからどんどん使って身につける。

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?