[Solved]-Django: how to include a static file in a template?

0👍

I have a couple of ideas.

The easiest thing to do would be to ensure you have the filesystem loader enabled, and you include the relevant directory containing static files in TEMPLATES[0]['DIRS'] (previously TEMPLATE_DIRS). The caveats are that it will not pick up static files contained inside your installed applications automatically, unless you list them in DIRS, too. Another option would be to use STATIC_ROOT, but that will only work if you run collectstatic every time you change the static file, which you normally don’t have to do in development. Another pitfall is that it will only work with local static storage, not if you use any CDN or otherwise host your static files on a different host / network / whatever.

The other thing you can do is to write your own template loader which will use the static files API to load statics as templates. This is a bit more involved, but it should be able to access static files regardless of how they are stored and served.

Should you choose either option, you still have to be careful. For instance, you’ll have to ensure that the static files you’re including as templates are safe to include into HTML or whatever other context you’re using them in. There will be no escaping going on.

In case you’re trying to optimize the number of requests the client has to make, there are better ways. You’re most likely better off implementing some pipeline that will pre-process and minify your static files. Including any significant chunk of CSS / JS into the HTML will make it impossible for clients to take advantage of caching, forcing them to re-download the same static content over and over again, likely impacting the performance negatively.

Edit: Since you want to just include some dynamic JavaScript variables, that’s not a static file at all. What you really want is to create a template containing JavaScript code, and not mess with handling static files as templates. There is no rule that would say every javascript needs to be a static file. If it’s dynamic, it’s not a static file.

For the record, this was a typical instance of the XY problem. Problem X was dynamically assigning values to JavaScript variables when rendering templates. You came up with including static files in templates as a potential solution, but then got stuck with problem Y, which was that you didn’t know how to include static files in templates.

6👍

The include directive only searches file in template directories. What you could do (although I wouldn’t) is to change your settings to also include the static files:

TEMPLATE_DIRS = [
    ...
    "path/to/your/statics",
]
👤Tzach

Leave a comment