[Answer]-Using Django constants in Javascript

1👍

That depends on where that JS is:

Embedded in a page’s HTML:

You can get away with pref/{{ ENABLE_T}}/0/ provided that you pass ENABLE_T in the context (see below).

In an external JS file

In your HTML, define:

<script>
    window.enable_t = '{{ ENABLE_T }}';
</script>

In your JS file, use

'pref/'+ window.enable_t + '/0/'

You’ll also need to pass ENABLE_T to the context.

How to pass ENABLE_T to the context

Use a Context Processor. You’ll need to define the processor, and add it to the TEMPLATE_CONTEXT_PROCESSORS setting, as shown in the docs

Why use a Context Processor?

You may also pass ENABLE_T directly to the context, in your view. However, this means that you have to do it in every view.

A context processor lets you avoid code duplication by automatically adding the constant to your contexts, whenever you use RequestContext – which you probably won’t even have to think about if you’re using Class Based Views.

0👍

You have several choices. Firstly, you can render javascript file as template so you can inject template variables to javascript. You can have django template like:

var my_variable="{{DJANGO_VARIABLE}}";
//do something with variable

.

Another choice is to render only variables and pass them for example by ajax on hardcoded url, or include variables in html template and at the and include javascript which operate on well defined variables. For example you define variable X and in script which you load you use this variable.

Yet another option is to use django javascript integration scripts (look at the django-admin scripts). There are some javascript functions defined to get for example some static variables or to reverse urls.

👤spinus

Leave a comment