Gr1N
Gr1N

Reputation: 1377

Using django template tags with JavaScript

How can I use Django's template tags within JavaScript? This is my code:

{% block scripts %}
<script>
    $(document).ready(function() {
        var classEditor = {
            dcg: $("div.control-group"),

            set: function(i, errors) {
                $dcg = $(classEditor.dcg[i]);
                $dcg.addClass("error");
                $dcg.children('div').children('div').children('p').text(errors);
            }
        };

        {% if form.email.errors %}
            {% for err in form.email.errors %}
                {{ e|add:err }}
            {% endfor %}
            classEditor.set(1, {{ e }});
        {% endif %}
    })
</script>
{% endblock %}

I want to send all errors to a function and do something with it. I tried to use striptags and stringformat, but it always raises errors.

Upvotes: 0

Views: 452

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

I don't think your problem has to anything to do with Javascript. The issue is here:

{{ e|add:err }}

This makes no sense at all. It seems like you're trying to build up a list, e, consisting of all the items in form.email.errors. But you can't do that sort of thing in a template - no data manipulation is allowed, by design. The add filter simply performs numeric calculations for display, it doesn't modify objects.

You probably want to serialize the errors to JSON in your view, and pass that JSON object to classEditor.set.

Upvotes: 1

Related Questions