Python Django 中的 {% block content %} 和 {% endblock content %} 是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53383602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:17:51  来源:igfitidea点击:

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

pythondjango

提问by Nazim Kerimbekov

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

所以我刚开始阅读一本关于 Django 的书(对于初学者),我遇到了以下代码片段:

<header>

<a href="{% url 'home' %}">Home</a> | <a href="{% url 'about' %}">About</a>

</header>

{% block content %}
{% endblock content %}

Could anyone possibly explain to me what is the use of {% block content %}and {% endblock content %}? Thank you very much in advance!

任何人都可以向我解释{% block content %}and的用途是{% endblock content %}什么?非常感谢您提前!

回答by Cup of Java

blockis used for overriding specific parts of a template.

block用于覆盖模板的特定部分。

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

在您的情况下,您有一个名为的块content,它应该被从该模板继承的子项覆盖。

From the examples at The Django Docs

来自The Django Docs的示例

Template to be extended, named base.html

要扩展的模板,命名 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"

“我的神奇网站”将被孩子覆盖,然后显示“我的神奇博客”

回答by markwalker_

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

从某种意义上说,这就是模板的力量的来源。

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

您可以创建模板的层次结构,因此从base.html上面可能会开始;

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

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

然后您可以创建任何其他模板,home.html例如,并执行类似的操作;

{% extends "base.html" %}

{% block content %}
    <h1>Welcome</h1>
    <p>This is the home page</p>
{% endblock content %}

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

然后你会引用home.html在Django和它会包括来自标记base.py与所限定的含量home.html

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

这是基础知识,但是如果您使用块将一些模板放在一起,您就会找到它。