kaya
kaya

Reputation: 1666

Building dynamic IMG URL in Django Template

i am new to Django and so far its okay, but i have difficulties building a dynamic URL.

<script>console.log("{% static 'img/emblem/league/scaled/league_' %}" + {{ league.id }} + ".png");</script>

this line works fine and output the correct link, in this case its

/static/img/emblem/league/scaled/league_1729.png

but in the following line when i try to build a dynamic URL to show different Images in a for loop, i get a TemplateSyntaxError when trying to do it with |add: as the "+" doesnt work either(images dont load)

<div class="owl-item"><img class="img-fluid" src="{% static 'img/emblem/league/scaled/league_'|add:{{ league.id }}|add:'.png' %}" alt="{{ league.name }}"></div>

TemplateSyntaxError at /matchstatistics/ add requires 2 arguments, 1 provided

I searched a lot and couldnt find a solution, thanks in advance.

Upvotes: 2

Views: 2799

Answers (3)

Zarrie
Zarrie

Reputation: 333

You can do it either using

get_static_prefix

Which I've not tested, but assume will work, if you static URLs are properly set in settings.py

or

<img src="{% static '' %}img/emblem/league/scaled/league_{{ league.id }}.png">

This one I've tested and works fine. It's essentially hacking the static command to return static url for the empty string which we then add before the dynamic path.

Upvotes: 1

kaya
kaya

Reputation: 1666

If anyone is interested, i solved it this way:

Create a file a new directory in your app directory, call it "templatetags" and create another .py file with the name of your html file. For example index.py for index.html.

from django import template
from django.conf.urls.static import static
from django.templatetags.static import static

from ..models import League

register = template.Library()

@register.simple_tag
def getLeagues():
    leagues = League.objects.filter(active=1)
    lgs = []
    for leagueObj in leagues:
        league = {
            "id": leagueObj.id,
            "name": leagueObj.name,
            "url": static('img/emblem/league/scaled/league_' + str(leagueObj.id) + '.png')
        }
        lgs.append(league)
    return lgs

and in the HTML file in your django templates, for me the index.html file.

   {% getLeagues as leagues %}
   {% for league in leagues %}
      <div class="owl-item">
          <a href="{% url 'matchstatistics:league' league.id %}">
             <img class="img-fluid" src="{{ league.url }}" alt="{{ league.name }}">
          </a>
      </div>  
   {% endfor %}

In summary what does this code? Shows Images in a carousel, once you click upon an element it calls another site with the given id for defined url route

Upvotes: 0

Karim N Gorjux
Karim N Gorjux

Reputation: 3033

I suggest you to create a template tag to manage the creation of the url of your image.

from django import template
from django.contrib.staticfiles.templatetags.staticfiles import static
register = template.Library()

@register.simple_tag
def get_img_url(img, *args, **kwargs):
    """Returns the img url of the given img

    .. usage::  {% get_img_url image_object %}

    """
    image_path = 'here you build your path using the img passed'
    return static(image_path)

More informations here: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#writing-custom-template-tags

Upvotes: 2

Related Questions