【问题标题】:javascript django html tagsjavascript django html 标签
【发布时间】:2016-10-04 02:05:18
【问题描述】:
var articles = [
    {% for article in article_list %}
        {% if not forloop.first %},{% endif %}
        {
            title: "{{ article.title }}",
            slug: "{{ article.slug }}",
            content: "{{ article.content }}",
            authors: [
                {% for author in article.authors.all %}
                     {% if not forloop.first %},{% endif %}
                     {
                     first_name: "{{ author.first_name }}",
                     last_name: "{{ author.last_name }}",
                     }
                {% endfor %}
            ]
        }
    {% endfor %}
    ]
]
$('#calendar').fullCalendar('addEventSource',articles);

这是位于 calendar-conf-events.js(fullcalendar) 中的代码,会导致错误 我将对象传递给 index.html (使用 calendar-conf-events.js ) 而且,在 JS 中我使用对象和模板标签,但是错误

错误是:“标识符或字符串文字或不需要数字文字” 原因在 {%

【问题讨论】:

  • 这个错误究竟是什么
  • 这是在.js 文件中吗?如果是这样,您不能在 .js 文件中使用模板标签。您可以将 javascript 代码移动到 .html Django 模板中,并将 javascript 包装在 <script></script> 标记中。

标签: javascript html django


【解决方案1】:

您不能像这样在.js 文件中使用模板标签。

我个人处理这种情况的方法是将我的 JS 代码移动到 Django 模板中,并将其包装在 <script></script> 标签中:

<script>
var articles = [
    {% for article in article_list %}
        {% if not forloop.first %},{% endif %}
        {
            title: "{{ article.title }}",
            slug: "{{ article.slug }}",
            content: "{{ article.content }}",
            authors: [
                {% for author in article.authors.all %}
                     {% if not forloop.first %},{% endif %}
                     {
                     first_name: "{{ author.first_name }}",
                     last_name: "{{ author.last_name }}",
                     }
                {% endfor %}
            ]
        }
    {% endfor %}
    ]
]
$('#calendar').fullCalendar('addEventSource',articles);
</script>

如果您正在访问articles,您可以将此代码移至index.html

更新:

由于您的 JavaScript 使用 jQuery,请确保提前加载该库,就像在其他地方加载一样。例如,您可以在模板顶部的 &lt;head&gt;&lt;/head&gt; 标签内添加以下内容:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>

【讨论】:

  • 谢谢,但是 "$('#calendar').fullCalendar('addEventSource',articles); "Cause Error "(index):363 Uncaught ReferenceError: $ is not defined"
猜你喜欢
  • 1970-01-01
  • 2021-03-29
  • 2013-08-12
  • 1970-01-01
  • 2013-02-17
  • 2016-05-18
  • 2015-12-26
  • 2012-09-27
  • 2014-04-06
相关资源
最近更新 更多