My jquery code works in html but not working when i move code in external js file. I figured out that probably django cannot render
{% if something %}
Why?
Usually we pass the flag in python to context, then render it as a hidden input or a hidden element, finally access the value of it via jquery:
in django,
your_flag = 'foo'
render(request, '[template]', {'flag': your_flag})
in templates,
<input type="hidden" name="flag" value="{{ flag }}" />
in js file,
var flag = $("[name='flag']").val()
if (flag === 'foo') {
// then do a lot of things
}
It doesn't work in a .js file because .js files are loaded "as is", not processed templates. So any templating code would be loaded verbatim and it will likely result in a parsing error in your js file. Check with firebug or chrome dev tools.
If you want your js to be processed by the templating system, you'll need to use{% include "subtemplate.js" %}, but you'll end up with inline code. Otherwise, you need to implement something along the lines of @iMom0.
rendermethod, it gets related html file and find all variables and functions (and anything that is python and django) and set variables, make condition check and render the output as their result. :In that situation, your js never rendered by django (so by python).