LoginSignup
2
1

More than 3 years have passed since last update.

Python jnjaテンプレート内でのデータの文字列変換の仕方

Last updated at Posted at 2020-10-21

最初に

 DjangoまたはFlaskフレームワーク内でjinjaテンプレートを使ってフロントエンドのHTMLを生成する際の覚書です。しばらくするとすぐに忘れてしまうのでここに書かせていただきます

やりたい事

  • 以下の2つを同時に行いたいです
    • Panda🐼s dataframeのデータを文字列に変換します
    • 文字列の最後が「計」の字であるかどうかを判断します
      • 「計」のある行は空白セルも含めて全て背景色を変えます

結論

Panda🐼s dataframeのデータを文字列に変換するには

  1. {% for 行 in df請求一覧[ 開始行NO : 終了行NO ].itertuples() %} で順にデータを取り出しに入れます
  2. の2列目のデータを 行[ 1 ] | string で文字列に変換します
    • これ以外の方法では私は文字列に変換出来ませんでした😢
      • エラーを吐いちゃうんですよね〜😣

前提条件

  • データは df請求一覧:Panda🐼s dataframe 形式
  • の字は各行の2列目
    • このdf請求一覧 がjinjaテンプレートを組み込んだHTML list.html に渡されます

データ形式

システム名 開発所属名 開発工数 請求金額
ほげシステム 風開発部 100.0 10000000
ほげシステム 水開発部 200.0 20000000
ほげシステム 土開発部 300.0 30000000
600.0 60000000
風システム 風開発部 100.0 10000000
風システム 水開発部 200.0 20000000
風システム 土開発部 300.0 30000000
600.0 60000000

ソースコード

list.html
  {% if df請求一覧.empty == None %}
    <div>請求一覧は表示できません</div>
  {% else %}
    <table class="small tablelock2">
      <thead>
        <tr>
          <th>NO</th>
          {% for 列名 in df請求一覧 %}
            <th>{{ 列名 }}</th>
          {% endfor %}
        </tr>
      </thead>
      <tbody>
        {% for  in df請求一覧[ 開始行NO : 終了行NO ].itertuples() %}
          <tr>
            {% for データ in  %}
              {% if ( データ == None ) %}
                {% if ( [ 1 ]|string ).endswith( '計' ) %}
                  <td class="littlesum"></td>
                {% else %}
                  <td class="data"></td>
                {% endif %}
              {% else %}
                {% if ( [ 1 ]|string ).endswith( '計' ) %}
                  <td class="littlesum">{{ データ }}</td>
                {% else %}
                  <td class="data">{{ データ }}</td>
                {% endif %}
              {% endif %}
            {% endfor %}
          </tr>
        {% endfor %}
      </tbody>
    </table>
  {% endif %}
2
1
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
2
1