In one of my templates, I have a for loop that goes over all the items. When a person likes or dislikes an item, I want to handle that with my function. Setting the button's HTML to something like this works:
<button onclick='update_like(arg1, arg2)'></button>{{ item.id}}
However, I need to pass my template variables to the function. So I tried something like this:
<button onclick='update_like({{item.id}}, {{item.name}})'></button>{{ item.name}}
But clicking the button just ouputs: Uncaught SyntaxError: Unexpected token 'default'
This is a trimmed down version of the full template I'm using:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="list">
{% for item in items %}
<button onclick='update_like({{item.id}}, {{item.name}})'></button>{{ item.name}}
{% endfor %}
</div>
<script>
var count = {};
function update_like(item_id, item_name) {
count[item_id] = 1;
console.log(count);
return;
}
</script>
{% endblock %}
Assuming item.id is number, item.name is string. You have to quote your value like this:
<button onclick="update_like({{item.id}}, '{{item.name}}')"></button>{{ item.name}}
To make sure above code is safe: replace '
to \'
(by a custom filter) in item.name
or not allow single quote in item.name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.