0

It is possible to have scripts tags in child pages and to be rendered by Django whey they (child pages are loaded / showed)?

I have a mobile web app which has this structure

ROOT
--PAGE1 (here I'd like to have the script rendered by Django)
--PAGE2
--PAGE3
--PAGE4

The reason is because on the second page I have custom controls like: flip switch, buttons, etc. that will do something specific on that page.

Code snippets:

//This one gets rendered only when root page is loaded
jQuery(document).ready(function($) {
        //But the control / html element its on the second page
        $("#myswitch").change(function() {
                console.log("Switch changed!");
        });
});

1 Answer 1

2

Sure. What you will need is a base template and a custom block for your end body scripts, here is an example:

base.html:

<html>
<head></head>
<body>
  <script src="/path/to/jquery.js"></script>
  {% block tail_scripts %}{% endblock tail_scripts %}
</body>
</html>

page1..4.html:

{% extends 'base.html' %}

{% block tail_scripts %}
<script src="/path/to/custom/script/if/needed.js"></script>
<script type="src/javascript">
  (function() {
    console.log('Build something awesome!');
  })();
</script>
{% endblock tail_scripts %}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for code snippets and pointing me to the right direction! I still have a question. Why the script doesn't get loaded only after I refresh the page and then the whole design breaks (css with jQuery because the path is invalid after refresh). No idea how to solve this...
What do you mean by the script doesn't get loaded? Is django producing a 404 on the resource or is the browser not executing it?
I've figure it out in the end with the path but now I've created a block in header and on my extended page I want to load another JavaScript file but it gets in the DOM only after I refresh the page. Any idea how to fix this? Thanks!
Fixed by putting the block inside page div as this answer says

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.