1

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?

1
  • 1
    "include" is part of the django template functionality. Which means it has to run through django template render engine, which means it needs to get folded into the final rendered file. But it can still be sourced from another file. Commented Nov 22, 2012 at 6:34

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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" %}

4 Comments

Still it will get rendered as inline script in the final rendered page. I want it to be an external file
You can keep the Scripts in external files and include it wherever you want in template.
As a part of web page speed optimzation, I need to "Thus, instead of inline JavaScript and CSS files, it’s best to place them in external files."
See as @jdi told Django templates with its context rendered at server side and it will come as inline when template rendered. You can put your JS and CSS as external files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.