0

How can I update a javascript variable and use it in a if statement?

<button onclick="hire = true">
    Hire
</button>

{% if hire %} //does not work
   <!-- print something -->
{% endif %}

<script>
    let hire = false;
</script>

I tried to declare the variable in views.py but then I can't update it in the template

  • 3
    You can't do that. Django is evaluated on the server and the result is send over the Internet to the client browser. JavaScript is evaluated on the client browser. –  Jun 15 '21 at 11:08

3 Answers3

1

Javascript is not aware of the server, and the server isn't aware of javascript. They're both isolated in their own environments: the client/browser, and the server.

If you want to cross this barrier, your best option is creating an API and using AJAX to fetch data from it. AJAX can keep communicating with the server even after the initial page load, making it possible to both send and recieve data.

Your use case isn't entirely clear, but the example you've given can be solved without involving the server at all. Simply use javascript to display or hide the hire section. Perhaps alpine.js could help you with this.

dellitsni
  • 417
  • 2
  • 9
0

It seems you want to control your page in browser and not in the server. In this case you need to use some JavaScript code instead of relying to django template.

Although you can do it by vanilla JavaScript, for same situations I tried alpine.js as a small library in front of bigger libraries like jQuery or Vue.js.

But as you may want to initial that 'hire' value you can put your initial value by Django template in an element value and read it by JavaScript later on browser.

0

You cannot use Javascript variable in django because:

  • Django template language works until the page is fully loaded with text from the backend.
  • Javascript works once the page is fully loaded as text.
  • Javascript don't know that there is a backend server serving the html pages.
  • Javascript don't work with backend.
  • Javacript only work with text/html(Dom).
Siva Sankar
  • 1,672
  • 1
  • 9
  • 16