[Django]-Is it ok to use Django Template Tag inside JS script

6👍

There’s nothing wrong with using a Django template tag inside a clump of Javascript. Django’s templating language is for the most part language-agnostic: it doesn’t care what the templated text means.

I’ve got rivers of Javascript with tons of tags, conditionals, variable substitutions, and so on.

Your other option for this sort of thing is to insert a Javascript boolean variable, and put the conditional in Javascript:

<script>
var is_project = {% if project %}true{% else %}false{% endif %};

//...

if (is_project) {
    // stuff for project
}
</script>

I suppose this keeps the Javascript cleaner. You’d have to decide based on your own code which style you prefer.

Leave a comment