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>
['japan', 'tokyo', 'osaka', 'nagoya', 'sapporo', 'sendai', 'fukuoka']
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