justajolt
justajolt

Reputation: 151

Why can't I pass the location of a static image file from my Django view to my html file using jinja templating?

I'm trying to add an image to an HTML page by passing the name of the .jpg file to an html jinja template from a view. The image is located in a static folder, and will appear as desired if the file name is coded directly, but not when I try to pass it in through Jinja.

Django view code:

def page(request):

   location = '''src="{% static 'image.jpg' %}"'''

   return(render(request, 'page.html', {'location':location})

Code on HTML page:

{% load static %}

<img {{location}} alt="image">

The image file is located in a static folder at the root of the Django project

I've also tried other combinations of string to be passed in and HTML including:

location = '''"{% static 'image.jpg' %}"'''
<img src={{location}} alt="image"> 

location = "'image.jpg'"
<img src= "{% static {{location}} %}" alt="image"> 

When I code the file name in directly as follows:

<img src= "{% static "image.jpg" %}" alt="image"> 

the image is presented as desired.

I feel like there is something I'm misunderstanding, but I'm not sure what. I couldn't find another question asking how to do this when I searched, so please forgive me if you know of an answer I didn't find!

Upvotes: 1

Views: 646

Answers (1)

justajolt
justajolt

Reputation: 151

OK... so this works:

location = "\image.jpg"

<img src= "{% static location %}" alt="things">

That extra slash at the start of the location variable name was what was missing! Can't believe it was that simple.

Upvotes: 1

Related Questions