Dynamically setting path to static file in Django

Viewed 274

In Django, I'm trying to dynamically set the path to a static JavaScript file in a subfolder parsed from the URL. Not sure if this a good way to do it in Django (i.e. best practice), or if I am completely off. It seems like way too many steps and not very DRY, especially the views.py code. Will Django allow me to parse the request in the view (base.html) template and bypass the views.py step? I could use JavaScript, but is it possible in Django?

Static file configuration has been defined in myproject/myproject/settings.py as:

STATIC_URL = '/static/'

My static files are set up as follows

Note: each main.js file contains scripts specific to that page.

/static/
└── js/
    ├── global.js
    ├── home/
    │   └── main.js  
    ├── projects/
    │   └── main.js  
    └── users/
        └── main.js  

If this is my URL:

http://example.com/projects

Views.py: I set a file path relative to my STATIC_URL path

def projects(request):
    context={'js_file':'js/projects/main.js'}
    return render(request, 'pages/projects.html',{'context':context})

Which I use in my base.html layout template to set the JavaScript path

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- template head content -->
</head>
<body>
    <!-- template content -->
    <script src="{% static context.js_file %}"></script>
</body>
</html>

This renders the following path

<script src="/static/js/projects/main.js"></script>
0 Answers
Related