user1852176
user1852176

Reputation: 455

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

Upvotes: 0

Views: 1159

Answers (2)

e4c5
e4c5

Reputation: 53734

Django can do what PHP can do, but better, more concisely and more readably :)

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

Where editing is passed to your template as

render(request, 'some_view_file.html',{'editing': true_or_false })

or it can come from a context processor.

Upvotes: 1

Jens Astrup
Jens Astrup

Reputation: 2454

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 %}

Upvotes: 1

Related Questions