2012-02-27 24 views
15

什麼是Django創建可重用模板的方式?如何在Django中創建可重用模板?

例如:假設我的很多頁面包含一個「最新消息」框並遵循DRY原則,我想定義它一次並在其他頁面中重複使用它。我將如何與Django(或Jinja2)模板做到這一點?

通過Django's Template Documentation閱讀中,我得到的印象是Django模板提供了「自頂向下」的繼承,其中子模板本身決定了超級模板,它會被嵌入:

<!-- Super-template (not valid, for illustration): --> 
<html> 
    <head><title>Title</title></head> 
    <body>{% block content %}{% endblock %}</body> 
</html> 
<!-- Sub-template: --> 
{% extends "base.html" %} 
{% block content %} 
<div class="latest-news">News</div> 
{% endblock %} 

那麼,什麼是幾個地方重用塊(子模板)的技術?

+2

使用電源的[包括(https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include)。 – 2012-02-27 20:54:54

回答

23

重複使用模板片段的最靈活的方法是define an inclusion_tag。您可以將參數傳遞給您的自定義標籤,在Python中處理它們,然後反彈回模板。 Direct inclusion只適用於不依賴於周圍環境的片段。

從文檔快速例如:

app/templatetags/poll_extras.py寄存器具有裝飾標記:

from django import template 
register = template.Library() 

@register.inclusion_tag('results.html') 
def show_results(poll): 
    choices = poll.choice_set.all() 
    return {'choices': choices} 

app/templates/results.html

<ul> 
{% for choice in choices %} 
    <li> {{ choice }} </li> 
{% endfor %} 
</ul> 

調用標記:

{% load poll_extras %} 
{% show_results poll %} 
+0

一個優點的'{%包括「xyz.html」%}'方法是可以確定哪個模板[在一個變量(https://docs.djangoproject.com/en/dev/ref/templates/builtins/ #include),例如'{%include template_name%}',其中'template_name'是包含模板名稱的變量。有沒有辦法用一個包含標籤來做到這一點?或者是在您包含的模板中添加包含標籤的最佳方式?例如,在頂層有模板'{%包括TEMPLATE_NAME%}'然後嵌套內的模板指向'template_name'具有'{%負載poll_extras%} {%show_results輪詢%}'。 – Chris 2015-12-24 00:17:27

9

如果您需要使用{% block %},則只能通過{% extend %}方法來實現。否則,您可以使用{% include 'some.html' %}在多個位置包含一些HTML。

1

非官方Django Reusable App Conventions建議使用這些塊名:

  • {% block title %}
  • {% block extra_head %}
  • {% block body %}
  • {% block menu %}
  • {% block content %}
  • {% block header %} {% block footer %}
  • {% block body_id %} {% block body_class %}
  • {% block [section]_menu %} {% block page_menu %}

如果每個人都堅持這些公約,就應該使這個問題更容易。按照鏈接查看每個塊的描述。