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?

4
  • what's the result of img src from your code? Commented Nov 14, 2013 at 10:41
  • Why downvote? without giving any suitable explanations? Commented Nov 14, 2013 at 10:45
  • @the5fire - Sorry, I didnt get you. Result of image source means? If you are talking about the source code from the webUI for <img> tag, then it is <img src="/static/img/icons/vendor/yahoo_weather/%7B%7Bvariable_int%7D%7D.gif" /> Commented Nov 14, 2013 at 10:47
  • yeah, I mean the source code from html for <img> tag. and I agree with @Daniel , the key point is static. Commented Nov 14, 2013 at 10:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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"}?

2 Comments

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 <img src="{% static "{{image_path}}" %}" />. And its not working
But why are you trying to use variable syntax inside a template tag? That doesn't work. Just do {% static image_path %}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.