[英]Django project, pure javascript, html and template tags best practices
[英]javascript django html tags
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代碼移到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,因此請確保以與在其他地方相同的方式提前加載該庫。 例如,您可以在模板頂部的<head></head>
標記內添加以下內容:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.