Django 3.1 Best way to Conditionally load statics

Viewed 22

I'm new to django and currently trying to find an effective way to load css files in the django templating language depending on the current page. The url pattern is :

path('invoices/', views.list, name='invoice_list'),
path('invoices/new/', views.create, name='create_invoice'),
path('invoices/<int:pk>/', views.edit, name='edit_invoice'),
path('invoices/<int:pk>/lines/new', views.create_line, name='create_line'),
path('invoices/<int:pk>/lines/<int:fk>', views.update_line, name='update_line'),

In the base.html, this is what i'm doing:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'invoice/css/common.css' %}">
    {% if request.path == '/invoices/'%}
       <link rel="stylesheet" href="{% static 'invoice/css/invoice_list.css' %}">
    {% endif %}
    {% if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path %}
       <link rel="stylesheet" href="{% static 'invoice/css/edit_invoice.css' %}">
    {% endif %}
    <title>My invoices </title>
  </head>

the {% if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path %} is not great at all and would like to know if there's a nicer way to do it regexp style maybe? Thanks in advance.

1 Answers

You should not put such logic in the template. Instead you should use the block and extends template tag for this purpose. See Template inheritance [Django docs]:

In base.html:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'invoice/css/common.css' %}">
    {% block extra_css %}
    {% endblock extra_css %}
    <title>My invoices </title>
  </head>

Now in the template which is rendered when if request.path == '/invoices/' is true, you will fill this block as:

{% extends "base.html" %}
...
{% block extra_css %}
    <link rel="stylesheet" href="{% static 'invoice/css/invoice_list.css' %}">
{% endblock extra_css %}

Similarly In the template which is rendered when if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path is true you you will fill the block as:

{% extends "base.html" %}
...
{% block extra_css %}
    <link rel="stylesheet" href="{% static 'invoice/css/edit_invoice.css' %}">
{% endblock extra_css %}
Related