簡體   English   中英

如何在 django 中使用模板塊?

[英]How can I use template blocks in django?

我正在嘗試使用 {% block %} 將 header 模板加載到我的索引中,但我無法加載它

索引.html

<body>

    <header>
        {% block header %}{% endblock %}
    </header>
<h1>Hello</h1>
</body>

header.html

{% extends "index.html" %}
{% block header %}
<div class="header">
    <a href="/category/"><i class="fas fa-archive"></i></a>
    <a href="../"><i class="fas fa-home"></i></a>
    <h1>hey</h1>
</div>
{% endblock %}

視圖.py

def index(request):
    categories = Category.objects.all()
    context = {'categories': categories}
    return render(request, 'category/index.html', context)

該應用程序已安裝在設置中。

為了實現你想要的,你現在應該渲染 header.html,檢查 django 文檔。

為了讓事情按照您想要的方式工作,您需要將 header.html 設置為基本模板,然后擴展 index.html 。 This is because header.html is only substituting in {% block header %} when you render header.html. Index.html 在渲染時看不到任何這些替換。 您可能希望將 header.html 文件制作為 static 文件並以這種方式加載它。 類似於您使用 css 的方式。

最好有一個布局,然后將 header 塊放入其中。

布局.html

...
<body>

    <header>
        {% block header %}{% endblock %}
    </header>
    <h1>Hello</h1>
    {% block content %}{% endblock %}
   <footer>
        {% block footer %}{% endblock %}
    </footer>


</body>
...

索引.html

{% extends "layout.html" %}
{% block header %}
   the header
{% endblock %}
{% block content %}
   here the content
{% endblock %}
{% block footer %}
   here the footer
{% endblock %}

現在您可以在視圖中渲染 index.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM