Home  >  Article  >  Backend Development  >  Using css and javascript in Django templates

Using css and javascript in Django templates

高洛峰
高洛峰Original
2016-10-17 14:16:441814browse

Use css, javascript in Django template

(r'^css/(?Ppath.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo /css'}),

(r'^js/(?P/pathpath.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo/ js'}),

(r'^images/(?P/pathpath.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo/images '}),

Use the following method in the template:

link href="/css/demo.css" type="text/css" rel="stylesheet"

Note: os.path can be used. dirname(globals()["__file__"]) to get the path of the current file, such as

(r'^css/(?Ppath.*)$', 'django.views.static.serve', {'document_root' : os.path.dirname(globals()["__file__"])+'/css'}),

You can use the os.path.abspath() function to return the absolute path of this path.

==============

To reference static files such as css, js, gif, etc. in django's template file, first turn on the DEBUG switch in setting.py.

1. Create a directory to store static files in the project directory, such as: medias

2. Add a line to url.py patterns:

(r'^site_media/(?Ppath.*)$',' django.views.static.serve',{'document_root':settings.STATIC_PATH}),

Also from django.conf import setting

3. Add a line to setting.py:

STATIC_PATH='./medias '

After setting this, you can reference the static files stored in media in the template file, such as:

img src='/site_media/django.gif'


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn