what is {% block content %} and {% endblock content %} for in Django?

后端 未结 2 1673
没有蜡笔的小新
没有蜡笔的小新 2021-02-07 01:49

so I just started reading a book on Django (for beginners) and I came across the following code snipet:

Home
相关标签:
2条回答
  • 2021-02-07 02:23

    block is used for overriding specific parts of a template.

    In your case, you have a block named content and this is supposed to be overridden by children that inherit from this template.

    From the examples at The Django Docs

    Template to be extended, named base.html

    <head>
        <link rel="stylesheet" href="style.css">
        <title>{% block title %}My amazing site{% endblock %}</title>
    </head>
    

    Overriding Child template

    {% extends "base.html" %}
    
    {% block title %}My amazing blog{% endblock %}
    

    "My amazing site" will be overriden by the child and then display "My amazing blog"

    0 讨论(0)
  • 2021-02-07 02:23

    That's where the power of the templates comes from in a sense.

    You can create a hierarchy of templates so start with base.html which might be like you've got above;

    <body>
        {% block content %}
        {% endblock content %}
    </body>
    

    Then you can create any other template, home.html for example, and do something like;

    {% extends "base.html" %}
    
    {% block content %}
        <h1>Welcome</h1>
        <p>This is the home page</p>
    {% endblock content %}
    

    Then you'd reference home.html in django and it'd include the markup from base.py with the content defined in home.html.

    That's the basics, but if you put some templates together using blocks you'll pick it up.

    0 讨论(0)
提交回复
热议问题