Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
Courses Plus 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.