【问题标题】:Django - SyntaxError when using {{ }} and {% %} tags in javascript functionDjango - 在 javascript 函数中使用 {{ }} 和 {% %} 标签时出现语法错误
【发布时间】:2015-08-01 03:28:49
【问题描述】:

我遵循 Django 网站上的教程,并尝试在 Django 网站的教程中的 results.html 创建级联下拉列表。

我在javascript函数中使用Django标签{{ }}{% %}时遇到了语法错误。我使用的 IDE 是 Komodo Edit,它将这一行 {% for item in question.choice_set.all %} 突出显示为红色并指出错误:Javascript: SyntaxError: expected expression, got '%'。

我想问一下,我该如何解决这个问题?

非常感谢!如下是我的 html 脚本。

results.html

<!doctype html>
<html>
<body>
<script type="text/javascript">
        function change(chosen,updateList){
            document.getElementById('text').value = chosen;
            updateList.options.length=0;
            {% for item in question.choice_set.all %}
                if (item = chosen) {
                    updateList.options[updateList.options.length] = new Option({{item.votes}}, '')
                }
            {% endfor %}
        }
</script>
<form name='form' action="{% url 'polls:results' quezstion.id %}", method='post'>
    {% csrf_token %}
    <h1>{{ question.question_text }}</h1>
    <select name="Choice" onchange="change(document.form.Choice.options[document.form.Choice.selectedIndex].value, document.form.Votes)">
        {% for item in question.choice_set.all %}   //question used here is defined in views
        <option value="{{item.id}}">{{ item.choice_text }}</option>
        {% endfor %}
    </select>
    <select name="Votes">
        <option></option>
    </select>
</form>

【问题讨论】:

  • 尝试在 stackoverflow 或谷歌搜索类似的答案:stackoverflow.com/questions/6008908/…
  • 嗨 taesu,我在发布问题之前阅读了此内容。它显示相同的语法错误:)
  • 只是为了理解,这只是IDE的错误吗?除此之外,这是否正常工作?乍一看还不错。
  • @Wtower,嗨。不,它不起作用:0

标签: javascript html django


【解决方案1】:

如果您想在嵌入式 js 中使用视图中的数据,您必须在视图中序列化此数据手动(例如我如何在项目中实现它):

从 CBV 获取上下文数据:(django 1.6 python 2.7)

 import json
 from django.utils.safestring import mark_safe
 # ...

 def get_context_data(self, **kwargs):
    context = super(LargeMapView, self).get_context_data(**kwargs)
    human_values = Human.objects.values(
        'pk', 'fio',
        'lat_deg', 'lat_min', 'lat_sec',
        'lon_deg', 'lon_min', 'lon_sec',
    )

    context['human_data'] = mark_safe(json.dumps(list(human_values), ensure_ascii=False))

    return context

部分模板:

 <script>window.jQuery || document.write('<script src="{% static 'js/jquery-1.11.1.min.js' %}"><\/script>')</script>

 <script type="text/javascript">
    var humanList = {{ human_data }};

    $.each(humanList, function (index, human) {
            var coords = getCoords(
                human['lat_deg'], human['lat_min'], human['lat_sec'],
                human['lon_deg'], human['lon_min'], human['lon_sec']
            );
    });
 </script>

【讨论】:

  • 这很好,但我无法理解这如何帮助解决相关错误。
  • @Wtower 我已经用 $.each 替换了 {% for ... %} {% endfor %} (也许那时我遇到了同样的问题......所以你可以称之为“解决方法") ... 也回答了 TS 下一个可能的关于序列化的问题 :)
  • @madzohan 嗨,谢谢你的建议,我会试试看:D
  • @madzohan,嗨!我能够将数据从我的视图传递到 html 并显示它。感谢您的解决方案!
猜你喜欢
  • 2023-01-08
  • 2015-08-22
  • 2018-11-16
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 2021-03-16
相关资源
最近更新 更多