0

I'm trying to display messages to the user when they login/signup using the alert function of javascript. I'm trying something like this, but it doesn't seem to work.

What is the correct syntax to pass django's variables to the script in a template?

This is what I want but this syntax doesn't work.

{% if messages %}{% for message in messages %}<script>alert({{}});</script>{% endfor %}{% endif %}

However the following is working:

{% if messages %}<ul>{% for message in messages %}
    <li>{{ message }}</li>
{% endfor %}</ul>{% endif %}
Dr Confuse
  • 605
  • 1
  • 7
  • 24

2 Answers2

1

Not sure as I can't test right now, but this should work:

{% if messages %}{% for message in messages %}<script>alert("{{ message }}");</script>{% endfor %}{% endif %}

Mind that alert stops the execution of JavaScript, so you will see one alert at the time. If you want all messages together you could use:

{% if messages %}<script>alert("{% for message in messages %}{{ message }}\n{% endfor %}");</script>{% endif %}

(Again, not tested)

But check this, I think it is a bit cleaner than the other solutions I proposed:

<script>
var messages = {{messages|jsonify}};
if (messages.length) alert(messages.join('\n'));
</script>
Community
  • 1
  • 1
natanael
  • 230
  • 1
  • 7
1

Django handles the template tags before Javascript is served - you can use the tags in Javascript in the same way you would with HTML, there's no difference since it all arrives to the client translated.

For example, here's what I use:

<script>
        {% if messages %}
            {% for message in messages %}
                Materialize.toast('{{ message }}', 4000);
            {% endfor %}
        {% endif %}
</script>

In your case, that's:

{% if messages %}
   <script>
    {% for message in messages %}
        alert("{{ message }}");
    {% endfor %}
   </script>
{% endif %}

Note the quotes around {{ message }} - Javascript will return an error if your message appears as alert(Hello World) instead of alert("Hello World"). I also moved the script outside of the for loop, though I don't think your way would cause any issues.

Though keep in mind if there are multiple messages, displaying alerts for each one may get annoying.

Jens Astrup
  • 2,415
  • 2
  • 14
  • 20