简体   繁体   中英

Javascript (string) Equality with Django Template

I'm new in Javascript and this is my html code that contain django template : I have img element which src attribute is "{% static 'basic/myImage.jpg' %}" which actually django template to load static file

<img src="{% static 'basic/myImage.jpg' %}" alt="img"/>

then i have script (javascript) let say main.js which aim is to select that img src attribute which will return literally "{% static 'basic/myImage.jpg' %}"

var myImg = document.querySelector('img');
var myImgSrc = myImg.getAttribute('src'); //return a string "{% static 'basic/myImage.jpg' %}"

my problem is when i try equality test in web console (inspecting element) :

myImgSrc === "{% static 'basic/myImage.jpg' %}" is return false

may be there is escape character or special character to represent my django template, can someone explain how to represent django template in literal js string. Thank you sorry for my bad english.

It's hard to tell exactly what you are trying to do, but I'll attempt to offer some suggestions.

When the template is rendered, {% static 'basic/myImage.jpg' %} is also rendered, so it becomes " /static/app/images/basic/myImage.jpg " or whatever. So your javascript evaluation will always be false.

If you need javascript to have the actual value returned by {% static 'basic/myImage.jpg' %} , then you will need to include the script in the template itself, rather than a separate main.js file.

So, at the bottom of your template.py file, you could have something like:

<script type="text/javascript>
    var myImg = document.querySelector('img');
    var myImgSrc = myImg.getAttribute('src');
    var Foo = "{% static 'basic/myImage.jpg' %}";
    if (myImgSrc === Foo) { // this should be true
        // do something
        }
</script>

Also, if main.js is included AFTER this script tag, it should have access to the values of myImgSrc and Foo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM