简体   繁体   English

在 Django 中使用模板特定的 JavaScript

[英]Using Template Specific JavaScript in Django

I have a base_generic.html page in django that has the standard UI elements (navbar, footer, etc.), and I have a list.html page which extends the base_generic.html page.我在django中有一个base_generic.html页面,它具有标准的 UI 元素(导航栏、页脚等),我有一个list.html页面,它扩展了base_generic.html页面。 The list.html page is using a javascript function that is only used in this page, but for it to work, I have to include it in the base_generic.html page. list.html页面正在使用仅在此页面中使用的javascript函数,但要使其正常工作,我必须将其包含在base_generic.html页面中。

How can I include this javascript function in list.html using Django's built-in template tags and features?如何使用 Django 的内置模板标签和功能在list.html包含这个javascript函数?

Should I use {% verbatim %} or {% scripts %} or another tag template?我应该使用{% verbatim %}还是{% scripts %}或其他标签模板?

Should I include this inline with the {% block content %} that has the html for this django template, or should I place it before or after the {% block content %} ?我应该将它与具有此django模板的html{% block content %}内联,还是应该将它放在{% block content %}之前或之后?

You have several ways of accomplish what you want:您有几种方法可以实现您想要的:

  • Just add the javascript snippet inside the {% block content %}只需添加里面的JavaScript片段{% block content %}

    {% block content %} {% 块内容 %}

    my javascript();我的 javascript();

    {% endblock content %} {% 端块内容 %}

  • Use the include statement to a file with your javascript, again, inside the {% block content %}再次{% block content %}使用include javascript 的文件

    {% include 'my_javascript.html' %} {% 包含 'my_javascript.html' %}

In this way, you can reuse your javascript code on other pages.通过这种方式,您可以在其他页面上重复使用您的 javascript 代码。

  • Create a new block in base_generic.html , like:base_generic.html创建一个新块,例如:

    {% block my_javascript %}{% endblock my_javascript %} {% block my_javascript %}{% endblock my_javascript %}

And in you child template, add the javascript as told in the first points iside these tags, in this case it can be outside or inside the {% block content %} .在您的子模板中,按照这些标签旁边的第一点中的说明添加 javascript,在这种情况下,它可以位于{% block content %}外部或内部。

An alternative would be pass the path for the js file in your views.py:另一种方法是在您的 views.py 中传递 js 文件的路径:

context = {
        'scripts_to_include':['/static/js/my_js_file.js']
    }

You can obviously include multiple js files here.您显然可以在此处包含多个 js 文件。 Then, in your template:然后,在您的模板中:

{% if scripts_to_include %}
   {% for script_url in scripts_to_include %}
      <script src="{{script_url}}"></script>
   {% endfor %}
{% endif %}

I like this, cause the js files can still be stored in a directory (instead of putting it right into html), JS files are also reusable.我喜欢这样,因为 js 文件仍然可以存储在一个目录中(而不是直接放到 html 中),JS 文件也可以重复使用。

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

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