How to load dynamically staticfiles CSS and Javascripts in Django

Asked

Viewed 19 times

-1

I’m writing in Python with Django. As a common practice, I created a "base.html" template that will then be extended by several other pages. Each one will have its own CSS file and its own Javascript file, so although they are "static" files, they are loaded dynamically according to the HTML doc. I found two solutions that both work but I don’t know if any of them will give problems later.
1st solution: Define a block for the lines with link and script tags; like this:
html base.:

<!DOCTYPE html>
<html lang="pt">
  <head>
...
{% block 'estilos' %}{% endblock %}
{% block 'scripts' %}{% endblock %}
...

html file.:

{% load static %}
{% block 'estilos' %}
<link rel="stylesheet" type="text/css" href="{% static 'nome_da_app/style.css' %}">
{% endblock %}
{% block 'scripts' %}
<script src="{% static 'nome_da_app/javascript.js' %}"></script>
{% endblock %}

The second solution led me to create a block only in the place where I upload the file, and it is the form I adopted and I am currently using:

html base.:

<!DOCTYPE html>
<html lang="pt">
  <head>
      <link rel="stylesheet" type="text/css" href="{% block 'estilos' %}{% endblock %}">
      <script src="{% block 'scripts' %}{% endblock %}"></script>
  </head>

html file.:

{% extends 'base.html' %}
{% load static %}
{% block 'estilos' %}
{% static 'nome_da_app/style.css' %}
{% endblock %}
{% block 'scripts' %}
{% static 'nome_da_app/javascript.js' %}
{% endblock %}

This last solution has a handicap that only now to explain the issue is that I realized: it only allows the loading of one and only one style file and Javascript.
But in terms of functionality, I think both will work properly?
By the way I took the opportunity to expose another problem I was having: the CSS changes I was making were not reflected and when I opened the style editor of the web programmer tools of my Firefox, nor the rules that were there were the current ones. " I saw myself Greek" until I could solve the problem!
SOLUTION: In the same web programmer tools, "Network" tab, there is a "Disable Cache" name checkbox that when activating me solved the problem.

PS: It’s my first publication, I’m sorry if it’ll be a little cramped, but I’ll get better in the future.

Regards and health to all!
Johnny

1 answer

0

Try it like this:

html base.

{% block scripts %}
<script src="caminho_1/script.js"></script>
...
<script src="caminho_N/script.js"></script>
{% endblock %}

Leaves at the base those that need to be on all pages, and the add-ons for specific pages, calls the block and adds on itself, like:

template_any.html

{% block scripts %}
<script src="caminho_extra_do_template/script.js"></script>
...
<script src="caminho_extra_do_template_N/script.js"></script>
{% endblock %}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.