简体   繁体   English

javascript django html标记

[英]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);

This is code located in calendar-conf-events.js(fullcalendar), and cause error I passing objects to index.html ( which use calendar-conf-events.js ) And, In JS I use objects and template tags, but error 这是位于calendar-conf-events.js(fullcalendar)中的代码,并且会导致错误,因为我将对象传递给index.html(使用calendar-conf-events.js),而且在JS中,我使用了对象和模板标签,但是出错

Error is : "identifier or string literal or no numeric literal expected" Cause at {% 错误是:“标识符或字符串文字或无数字文字”的原因为{%

You cannot use template tags in a .js file like this. 您不能在.js文件中使用模板标记,例如这样。

The way I personally have handled this type of situation is to move my JS code into a Django template, and wrap it in <script></script> tags: 我个人处理这种情况的方式是将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>

It sounds like you might be able to move this code into index.html if that is where you are accessing articles . 听起来,如果您正在访问articles ,那么您可能可以将此代码移至index.html

Update: 更新:

Since your JavaScript uses jQuery, make sure to load that library ahead of time the same way you would do it elsewhere. 由于您的JavaScript使用jQuery,因此请确保以与在其他地方相同的方式提前加载该库。 For example, you could add the following inside your <head></head> tags at the top of your template: 例如,您可以在模板顶部的<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.

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