LoginSignup
2
2

More than 1 year has passed since last update.

【Django】{% static %} タグ内で変数を使う方法

Last updated at Posted at 2021-12-29

【Django】{% static %} タグ内で変数を使う方法

staticから画像を読み込むとき、view.py から持ってきた変数を使って、
静的ファイルの表示を切り替えようと思って、ちょっと苦戦したのでやり方をいくつか紹介

詳しく

  • ユーザの個人ページにて、ユーザのトップ画像をユーザごとに表示する実装を行っている
views.py
def index(request):
    image_path = request.user.set_image_path
    return render(request, 'main/index.html', {'image_path': image_path})

Requestしたuserのset_image_pathフィールド(CharField)をimage_pathという変数に入れて
template に 渡す
image_path の中身 例 : user1_icon.jpg

  • template ファイル内の {% static '' %} 内で変数を入れようとしたけど、表示できない
index.html
{% extends 'main/base.html' %}
{% block content %}
{% load static %}
<h2>UserImage↓</h2>
<img src="{% static 'assets/userimages/{{ image_path }}' %}">
{% endblock %}

→これだと変数ではなく文字列{{ image_path }}と認識されるので、
当然そのようなファイルはなく404のエラーが返ってきて表示できない

↓エラー内容
[29/Dec/2021 18:10:10] "GET /static/assts/userimages/%7B%7B%20image_path%20%7D%7D HTTP/1.1" 404 1870

変数の使い方

参考にしたページ:
- django 1.5-静的タグ内で変数を使用する方法
- Djangoのテンプレート内で変数を設定する方法

方法1. テンプレートタグ「with」 & ビルトインフィルター「add:」 を使って変数をセットする

index.html
{% with 'assets/characters/'|add:image_path as image_static %}
<img src="{% static image_static %}" class="monster-img">
{% endwith %}

with タグは 変数を事前に設定して、タグ内だけで利用できる
add: フィルターは、指定した内容を|より前のものにadd する
今回はCharなので、連結されるけど、数字の場合は足し算される ( {{ 4|add:2 }} → 6になる)
他にもいろいろフィルターある→公式リファレンス

方法2. ビルトインフィルター「add:」を活用する

↑の省略形?みたいな感じ
今回はこちらを採用
一番すっきりしてるし、スマートな表記かなと思う

index.html
<h2>UserImage↓</h2>
<img src="{% static 'assets/characters/'|add:image_path %}" class="monster-img">

方法3. asを使って static の ベースURLを変数として最初に宣言 → {{ 変数 }}/{{ 変数 }}の形にする

これもなかなかすっきりして良い

index.html
{% static "assets/userimages" as baseUrl %}
<h2>UserImage↓</h2>
<img src="{% static '{{ baseUrl }}/{{ image_path }}' %}">

終わりに

as が便利だなと思った 今後活用する機会たくさんありそう
ビルトインフィルターも、使い方覚えれば応用が利きそう!

2
2
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
2