0

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

2
  • @cody4321 what exactly do you mean by "the code is now broken"? Does it return an error? Commented Aug 12, 2015 at 5:48
  • clicking on the body element no longer opened a window. I went into the Chrome JS console and didn't see any errors. What are the tools you use to see errors? I never know why the JS is breaking Commented Aug 12, 2015 at 12:54

1 Answer 1

1

{% 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>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks Frank I'll check if that was the only issue soon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.