Reputation: 9672
I have a JS snippet that works and used in several files:
<script>
{% if not articles %}
var url = {% url 'index:new-article' %};
$('body').on('click',function(e){
window.location = url
});
;
{% endif %}
</script>
But if I put that code in a separate file 'main.js' and load it into the template, it will no longer work. It is now in 'main.js' as such:
var url = {% url 'index:new-article' %};
$('body').on('click',function(e){
window.location = url
});
;
but when loaded like:
{% if not articles %}
<script src="media/js/main.js"></script>
{% endif %}
in 'mytemplate.html', the code is now broken. Others advise simply including JS files you want to use into your django templates (best practice including javascript in django template). How can I use some template logic like my "if not this, include js file" and make it work? Thank you
Upvotes: 0
Views: 488
Reputation: 1342
{% url 'index:new-article' %}
will return the raw string, you have to quote its output for it to be valid Javascript.
<script>
{% if not articles %}
var url = '{% url 'index:new-article' %}';
$('body').on('click',function(e){
window.location = url
});
;
{% endif %}
</script>
Upvotes: 1