[PYTHON] How to pass values to JavaScript variables directly from the [Django] template tag

Background

If you want to display as it is in html from context_data of TemplateView, you can display it by setting the tag as follows.

views.py


from django.views.generic import TemplateView

class SampleTemplateView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['areas'] = ["japan","tokyo","osaka","nagoya","sapporo","sendai","fukuoka"]
        return context

index.html


...
    <ul>
    {% for item in areas %}
        <li> {{ item }} </li>
    {% endif %}
    </ul>
...

Is displayed.

However, there are times when you want to pass a value directly when you want to draw using the Javascript library. Here's how to pass it.

Failure

If you pass it as it is, ...

<script type="text/javascript">
    var areas = "{{ areas }}";
    console.log(areas);
</script>
[&#x27;japan&#x27;, &#x27;tokyo&#x27;, &#x27;osaka&#x27;, &#x27;nagoya&#x27;, &#x27;sapporo&#x27;, &#x27;sendai&#x27;, &#x27;fukuoka&#x27;]

Single quotation marks, "<", ">", etc. are automatically converted. Since it is a string type, I thought it would be okay to dict it with JSON.parse after replacing it with a regular expression, but I couldn't do it well.

So, as a result of my research, I found two methods.

Method 1 It's muddy, but it's a way to call each element and write it in javascript code.

var areas = [
{% for area in areas %}
{% with index=forloop.counter0 %}
{% if 0 < index%},{% endif %}
{% endwith %}
"{{area.name}}"
{% endfor %}
];
console.log(areas);

Method 2

The other is to turn off the automatic escape control with ʻautoescape`.

{% autoescape off %}
var areas = {{ areas }};
{% endautoescape %}
console.log(areas);

This one is easier.

Reference

-Django Official Page Built-in Tags and Filters -Display Django Template HTML tags without escaping

Recommended Posts

How to pass values to JavaScript variables directly from the [Django] template tag
[Python] How to remove duplicate values from the list
How to do the initial setup from Django project creation
How to do arithmetic with Django template
How to check the version of Django
How to operate Linux from the console
How to build an application from the cloud using the Django web framework
How to count the number of elements in Django and output to a template
How to print debug messages to the Django console
How to operate Linux from the outside Procedure
How to measure line speed from the terminal
Wagtail Recommendation (4) Let's pass the context to the template
How to find the correlation for categorical variables
How to pass arguments when invoking python script from blender on the command line
How to create an article from the command line
The wall of changing the Django service from Python 2.7 to Python 3
How to use Azure Table storage from Django (PTVS)
DJango Note: From the beginning (creating a view from a template)
How to instantly launch Jupyter Notebook from the terminal
Execute Python function from Powershell (how to pass arguments)
Transit to the update screen with the Django a tag
How to post a ticket from the Shogun API
[Python] How to output the list values in order
[Django] How to redirect unlogged-in users to the login page
Django # 2 (template)
Django Template notes
Django HTML template
Django template file organization
Django memo # 1 from scratch
DJango Note: From the beginning (creating a view from a template)
Django starting from scratch (part: 2)
Django starting from scratch (part: 1)
Use django model from interpreter
Show Django ManyToManyField in Template
DJango Memo: From the beginning (preparation)
[Beginner] Get from Django Query database
Get the value from the [Django] Form
Make a filter with a django template
How to pass values to JavaScript variables directly from the [Django] template tag
How to set variables that can be used throughout the Django app-useful for templates, etc.-
How to write custom validations in the Django REST Framework
[Django] Pass the user instance authenticated by API to ModelSerializer
[Django] How to give input values in advance with ModelForm
How to calculate the amount of calculation learned from ABC134-D
How to log in automatically like 1Password from the CLI
(Note) How to pass the path of your own module
How to generate a query using the IN operator in Django
How to hit NAPALM from the Web (NetDevOpsSec reality solution)
How to use discrete values as variables in Scipy optimize
DJango Memo: From the beginning (more edits to the management screen)
Pass OpenCV data from the original C ++ library to Python
Report (maybe) changes from Django 2.x to Django 3.x: How to specify static file tag rewriting and HttpResponse Redirect
How to use the generator
How to define Go variables
Pass text to Django genericview
How to use the decorator
How to increase the axis
How to start the program
How to get all the possible values in a regular expression
How to get followers and followers from python using the Mastodon API
[Python] How to get & change rows / columns / values from a table.
[EC2] How to install and download chromedriver from the command line
[Django] How to read variables / constants defined in an external file
How to extract the desired character string from a line 4 commands
How to resolve the error from toimage (from PIL.Image import fromarray as toimage)
How to use the render function defined in .mako (.html) directly in mako
[Tips] How to do template extends when creating HTML with django
How to fix the shit heavy when reading Google Cloud Storage images from Django deployed on GAE