且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在django模板中复制数据的***方法是什么?

更新时间:2023-02-09 16:00:20

像你的布局是坚实的。您有一个 base.html 模板,它定义了应用程序中每个页面的基本结构和外部布局。您还可以扩展此模板的 base_object.html

It looks like your layout is solid. You have a base.html template that defines the basic structure and outer layout for each page in your app. You also have base_object.html that extends this template.

您希望每个页面都有一个唯一的标题和一个匹配的h1(我想)。这样做的***方法是在base.html模板中定义两个单独的块。

You'd like each page to have a unique title and a matching h1 (I think). This best way to do this is to define two separate blocks in your base.html template.

<html>
    <head>
        <title>{% block title %}Default Title{% endblock %}</title>
    </head>

    <body>
        <h1>{% block h1 %}{% endblock %}</h1>
    </body>
</html>

在您的子模板中,如果您希望它们相同,则需要覆盖这两个模板。我知道你觉得这是反直觉的,但是由于Django中处理模板继承的方式是有必要的。

In your child templates, you need to override both of these if you'd like them to be identical. I know you feel this is counter-intuitive, but it is necessary due to the way template inheritance is handled in Django.

资料来源: Django模板语言


最后,请注意,您不能在同一模板中定义具有相同名称的多个 {%block%} 标签。存在此限制,因为块标记在两个方向上工作。也就是说,块标签不仅仅是提供了一个填充孔,而且还定义了填充父节点的内容。如果模板中有两个类似命名的 {%block%} 标签,该模板的父级将不知道要使用哪个块的内容。

Finally, note that you can't define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill -- it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %} tags in a template, that template's parent wouldn't know which one of the blocks' content to use.

孩子们看起来像这样:

{% extends "base.html" %}
{% block title %}Title{% endblock %}
{% block h1 %}Title{% endblock %}

如果这使您烦恼,您应该将每个对象的视图中的标题设置为模板变量。

If this bothers you, you should set the title from the view for each object as a template variable.

{% block title %}{{ title }}{% endblock %}
{% block h1 %}{{ title }}{% endblock %}

Django力求尽可能多地保留模板层中的逻辑。通常,从数据库动态确定标题,因此视图层是检索和设置此信息的完美场所。如果您想继续使用默认标题(也许设置在 base.html 中),您还可以将标题留空,或者您可以从 django.contrib.sites package)

Django strives to keep as much logic out of the template layer as possible. Often a title is determined dynamically from the database, so the view layer is the perfect place to retrieve and set this information. You can still leave the title blank if you'd like to defer to the default title (perhaps set in base.html, or you can grab the name of the site from the django.contrib.sites package)

另外 {{block.super}} 可能派上用场。这将允许您将父区块的内容与子节点的其他内容进行组合。所以你可以在基地定义一个标题,如***.com,并设置

Also {{ block.super }} may come in handy. This will allow you to combine the contents of the parent block with additional contents from the child. So you could define a title like "***.com" in the base, and set

{% block title %}{{ block.super }} - Ask a Question{% endblock %}

获得标题像***.com - 提问

in the child to get a title like "***.com - Ask a Question"