user1852176 user1852176 - 1 month ago 4
Javascript Question

Check for variable in Django template

I'm new to Django and coming from a PHP background. When I was dealing with pages to enter content and later be able to edit it (and the pages rely on some JS files), I would just set a variable from the controller and let my view (view in the PHP MVC sense) handle it based on the variable being set. That way I could use the same javascript file for both the create and edit pages, rather than two separate JS files with only minor differences. For example

/some_view_file.html

<?php
if(isset($editing) && $editing == true){
?>
<script>var editing = true; </script>
<?php
}
else{
?>
<script>var editing = false; </script>
<?php
}
?>


Since Django seems to be focused on templating rather than being able to intermittently write Python/HTML like you can with PHP/HTML, is there any way to accomplish what I've shown above?

I suppose a better question is how do Django programmers typically handle situations like this?

Thanks

Answer

It's been a while since I've used PHP, but if I understand what you're trying to achieve, you want the if/else template tags:

{% if editing %}
    <script>var editing = true; </script>
{% else %}
    <script>var editing = false; </script>
{% endif %}
Comments