I am trying to load a specific image using javascript in a django template, but seem to be running into an issue based on the way django tags are formatted.
I have a standard django static asset source in an img tag like below:
{% load static %}
<img src="{% static 'img/folder/logo1.svg' %}" id="orgLogo" alt="Logo" height="100px"/>
I am displaying data from django lower on the page like so:
<a id="orgName" class="side_nav_item">{{ thing.org_name }}</a>
What I would like to do is have the img src change based on the value of thing.org inside the django tags.
I originally thought jquery would be the best option, but it doesn't seem to play nice with django tags:
$(document).on('load', '#orgName', function(){
$('img').attr('src','{% static 'img/folder/''+$('#orgLogo').val()+' %}');
});
I get error because of the single quotes required as part of the django syntax.
I after I was able to get the basics of this javascript function to work, I was planning on using a javascript switch statement to test for specific values and assign an image (e.x. logo1.svg, logo2.svg, etc.) to each value (e.x. org1, org2, org2) thing.org can load (it's a pre-defined set of values that's not long and not likely to change).
Any suggestions on how to approach this?
thing.org_namein a JS var and then use that var instead of the string itself?{% static %}template tag is evaluated by your back-end, when producing an HTML document. It doesn't exist on the front-end so it's not available anymore when your HTML/javascript reaches the browser and your javascript runs. So: create a dummy URL javascript variable (var baseURL = "{% static 'img/folder/ %}") somewhere, and in your javascript manipulate this baseURL by appending the correct value.