简体   繁体   English

将 Django 模板变量传入 JS function

[英]Pass in Django Template Variable to JS function

In one of my templates, I have a for loop that goes over all the items.在我的一个模板中,我有一个遍历所有项目的 for 循环。 When a person likes or dislikes an item, I want to handle that with my function.当一个人喜欢或不喜欢某件物品时,我想用我的 function 来处理它。 Setting the button's HTML to something like this works:将按钮的 HTML 设置为如下所示:

            <button onclick='update_like(arg1, arg2)'></button>{{ item.id}}

However, I need to pass my template variables to the function.但是,我需要将我的模板变量传递给 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'但是单击按钮只会输出: 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.假设 item.id 是数字,item.name 是字符串。 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为确保上述代码安全:将item.name ' \' item.name引号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM