简体   繁体   English

在Django HTML模板中包含html,css,js小部件

[英]Include html, css, js widget in Django html template

I have a Google maps "widget" that includes html, css, and javascript that will need to be present everywhere that this map is used. 我有一个包含html,css和javascript的Google地图“小部件”,在使用此地图的所有地方都将需要显示它。 As such I'm looking for a way to extract these components into one widget like file and simply include this file wherever I want to use the map. 因此,我正在寻找一种将这些组件提取到文件之类的小部件中的方法,并在需要使用地图的任何地方简单地包含此文件。

I have already considered: 我已经考虑过:

  • making the three components three separate files to be included. 使这三个组件包含三个单独的文件。 This is currently my fall back solution as I would like to have it be just one file. 目前,这是我的后备解决方案,因为我希望它只是一个文件。

  • including the css and javascript in the header and then using the javascript to add the desired html to an element that exists on the page. 在标头中包含css和javascript,然后使用javascript将所需的html添加到页面上存在的元素中。 This seems like a hack solution and it would be done client side as such it would be slower than if the html were included server side. 这似乎是一个hack解决方案,它将在客户端完成,因此比在服务器端包含html还要慢。

  • and the solution proposed for this question: How to include plug-n-play widget statics [CSS/JS] without repetition? 以及针对该问题提出的解决方案: 如何不重复地包含即插即用小部件静态[CSS / JS]? But like the person asking that question I would like a better solution than simply creating a new base template. 但是,就像问这个问题的人一样,我希望有一个比单纯创建新的基础模板更好的解决方案。

My previous attempts have included creating an html file with the necessary code and {% include "maps-widget.html" %} in both the header and in the desired location. 我以前的尝试包括使用必要的代码创建一个html文件,并且在标头和所需位置中{%包括“ maps-widget.html”%}。 In both attempts it stated that google api that is included in the widget was not present. 在这两次尝试中,它都表明不包含在小部件中的google api。

I am running python 2.7 and Django 1.5.4. 我正在运行python 2.7和Django 1.5.4。

You can put the HTML, CSS, JS in the Base template for the project, and then it will be present in all of you pages. 您可以将HTML,CSS,JS放入该项目的基本模板中,然后它将出现在您的所有页面中。 Here is the Django Docs showing how: 这是Django文档,显示了如何:

http://www.djangobook.com/en/2.0/chapter04.html http://www.djangobook.com/en/2.0/chapter04.html

A typical implementation for CSS / JS would look like this: CSS / JS的典型实现如下所示:

<!-- Your base.html file -->

{% block static %}

  Your CSS Files go here

{% endblock static %}

{% block content %}

  This can be a default value, but otherwise your template will override it

{% endblock content %}

{% js block %}

  Your JS files / links

{% endblock js %}

And now just extend your base.html template and it will inherit all of the the CSS / JS files 现在,只需扩展您的base.html模板,它将继承所有CSS / JS文件

<!-- myTemplate.html -->

{% extends "base.html" %}

{% block content %}

  Your Google Map content, etc...

{% endblock content %}

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

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