1

I want to pass a variable from python Django and use it inside the <img> tag. How can I do it?

Here is my code.

Python-

render(request, 'dashboard/dashboard.html', {"variable_int" : 12})

HTML

<img src="{% static "img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}" /></td>

I know that I need to pass it between {{}} but I'm not getting the image. How can I do it?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
python-coder
  • 2,128
  • 5
  • 26
  • 37

2 Answers2

3

You have not described the problem properly at all. The issue isn't passing it to the template, which is an absolutely basic issue that you obviously already know how to do, but how to use it within a string inside the static tag, which is a completely different question.

The answer is, you can't easily. But why wouldn't you pass the whole path? Why not {"img_path": "img/icons/vendor/yahoo_weather/12.gif"}?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I tried this. `image_path = "img/icons/vendor/yahoo_weather/" + str(weather_image_code) + ".gif"` `render(request, 'dashboard/dashboard.html', {"image_path" : image_path})`. And inside template I wrote ``. And its not working – python-coder Nov 14 '13 at 10:54
  • 2
    But why are you trying to use variable syntax inside a template tag? That doesn't work. Just do `{% static image_path %}`. – Daniel Roseman Nov 14 '13 at 10:56
3

The problem is django first convert the url, and then you don't have any variable on the code.

Django change this:

{% static "img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %} 

for this:

"/static/img/icons/vendor/yahoo_weather/%7B%7Bvariable_int%7D%7D.gif"

Django first call the "function" to get static urls, and change all the code inside. You can try to call a variable {{ STATIC_URL }} (if you have it defined on settings.py), that variable will get the path for the static folder, and after it will get the value of the variable.

Try this:

<img src="{{ STATIC_URL}}img/icons/vendor/yahoo_weather/{{variable_int}}.gif" %}" /></td>

In this case django should make 2 changes, {{ STATIC_URL}} and {{variable_int}} instead of just one.

AlvaroAV
  • 10,335
  • 12
  • 60
  • 91