Using constants in templates

In the same directory as settings.py I created a file called icons.py It contains icon constants:

LIST = ‘fa-regular fa-rectangle-list’

I want to use these constants in my templates:

Is this possible in Django?

Kind regards,

Johanna

You have at least two options here, that both work out to effectively the same thing.

First, in either case, for any data to be used within a template by the rendering engine, that data needs to be made known to that engine.

Typically, that process of making data available to the engine is done by passing it in through the context.

So, your first option would be to import your icons module in your view, and then add those values to your context.

If this is something that is going to be used in multiple views across multiple files, you might want to make them more “globally” available. To do that, you would want to add those values using a context_processor. (This is the second option.)

In either case, I would actually recommend that you not store these in files. If I were faced with a situation like this, I would most likely create a table for them, and add the queryset for that table to the context. (It potentially provides for a lot more flexibility and ease of maintenance.)

Hi Ken,

I apologize for not replying to your answer to my question directly.

I am considering creating a table, as you recommend.

Kind regards,

Johanna

Hi Johanna,

No worries! Replies aren’t always necessary.

We’re here to help, feel free to return with any further questions.

Ken