1

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?

1
  • Because when django call a render method, 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). Commented Nov 26, 2013 at 14:54

2 Answers 2

3

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

1 Comment

handlebars maybe another solution, you can try it.
0

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.

Comments

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.