Vivek S
Vivek S

Reputation: 5550

use django variables in external script files

I am having a lot of scripts written inline along with the HTML. Now, I am trying move the scripts to an external file. But, most of my scripts uses django variables and if.else statements. So, I am not able to move these scripts to an external files. Is it possible to use django template variables/conditions in scripts loaded from external file?

Upvotes: 1

Views: 876

Answers (2)

jdi
jdi

Reputation: 92617

What you are asking for is a client-side include, in order to ultimately retain the external file as a "link". That means the main page loads, and then the external content is loaded, all client side. Yet you want the include to be django-processed.

Django templates are rendered server-side, meaning that they have to be evaluated with the context, server side. The main page has to fold the includes into it in order to serve it to the client. Thus, what you are asking for is possible, if you accept that you can keep your content in external files, but they will be rendered in the same page.

Otherwise, you would have to do something more complicated like have javascript load the external pages, passing the same context information back to the server, which can render the template through a different url endpoint. Or just rely on the session data, and have the other url render its page completely on its own.

Upvotes: 1

Ahsan
Ahsan

Reputation: 11832

Did you use include. Make an another html file and include it parent template.

You can pass additional context to the template using keyword arguments:

{% include "name_snippet.html" with person="Jane" greeting="Hello" %}

Upvotes: 0

Related Questions