codyc4321
codyc4321

Reputation: 9672

using django template logic in loaded JS files (integrate django JS)

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

Answers (1)

frank
frank

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

Related Questions