Python Flask Basics Templates and Static Files Static Files

What's the point of {% block scripts %} in layout.html?

After he moves the {% block scripts %} <script src="/static/scripts.js"></script>{% endblock %} code from layout.html, he keeps an empty block in layout.html. What's the point of this? Wouldn't it make more sense to remove this block and use <script src="/static/NAME_OF_SCRIPT.js"> on any page where a script should appear?

Hara Gopal K
Hara Gopal K
Pro Student 10,027 Points

hey krystal,

did you happen to find out the answer ?, i have the same question too...couldn't find the answer in the community,

1 Answer

Ronald Lira
Ronald Lira
12,216 Points

A couple of comments here:

  1. "layout.html" is your template. Now, "index.html" needs to pass information to "layout.html", but it needs a reference to know where to put the code. That is why you need {% block scripts %}{% endblock %} in your "layout.html" . It is "empty", yes!, but without it how does ninja2 knows where to put your code?

  2. Yes, you can do <script src="/static/NAME_OF_SCRIPT.js">, without the {% block scripts %}{% endblock %}. In this case your NAME_OF_SCRIPT.js will be loaded everytime you call "layout.html". If this is what you want, that is OK. However, if you want more control over which scripts are called/executed on different pages, then it is better to use the {% block scripts %}{% endblock %} statement. Imagine you have your "layout.html", "page1.html" and "page2.html" and you have 3 different scripts. Let say you want to run script0.js in all pages, script1.js in page1.html and scrip2.js in page2.html. You can put your script0 directly in your layout.html and then use {% block scripts %}{% endblock %} to dynamically call script1 or scrip2 depending on which page is called.

Hope this helps.