how to assign the value of a variable django to a variable in angularjs

0

Greetings, I have the following problem with my django application, I use swwetAlert to show messages in my web interface, but I want the message that is generated in my view to be displayed in my template, for this I need to store in a javascript variable the information in a variable django, how could this be done, in the code below, the information that has the variable menssage I want to show in the notice, how can I do this.

{% if menssage %}
    <script language="JavaScript" type="text/javascript">
        sweetAlert({
            title: "Error!",
            text: menssage,
            type: "error",
            confirmButtonClass: 'btn-danger',
            confirmButtonText: 'Aceptar'
        });
    </script>
{% endif %}
    
asked by Luis Antonio García González 09.01.2018 в 20:46
source

1 answer

1

As long as the file to which you want to show Django or server data, is a file that Django deals with directly, that is, that passes through the Django template engine and is not generated by a framework on the side from the front like Angular, React, Vue, etc. That is, as long as you have direct contact with django, you can replace it in the same way you normally do, in your case it would look like this:

{% if menssage %}
<script language="JavaScript" type="text/javascript">
    sweetAlert({
        title: "Error!",
        text: '{{ menssage }}',
        type: "error",
        confirmButtonClass: 'btn-danger',
        confirmButtonText: 'Aceptar'
    });
</script>
{% endif %}

You have to be careful because many of these frameworks to treat the templates usually use the same syntax or nomenclature as Django, as in the case of Vue, that to replace attributes or variables within the template also does so by means of {{ and }} and this may cause rendering problems on behalf of Django.

You can think what happens next: When your view returns the render, django looks for a file of .html which you passed through the function, and next to some data that you pass through the RequestContext , the django templates engine starts looking for all matches of {{ }} and makes a match of the dictionary of RequestContext with the word that is between the keys, thus replacing the content, and not finding a match , simply replace it with an empty string.

So, it is important to remember that at that point, no javascript code can be executed, since the django template engine does not execute the html file code. So when I'm going to return that file to the server, all your variables with {{ }} will be replaced with an empty string, and nothing will work for the javascript that interferes with that. It's a complicated thing to explain, I hope you made me understand in case you had doubts.

Any questions, ask:)

    
answered by 11.01.2018 / 03:26
source