2017-02-11 136 views
1

我有一個Django模板,我們稱之爲index.html,它被分爲3部分(標題,內容和頁腳)。在標題部分,我有一個搜索欄,其中包含一個下拉菜單,允許用戶從中選擇一個選項並根據所選選項搜索內容。我希望將這個標題部分包含在我以後的所有視圖/模板中,並且仍然顯示包含所有選項的下拉菜單。Django如何重用所有視圖通用的視圖功能

這是我目前在我的視圖文件

def index(request): 
    return render(
        request, 
        'home.html', 
        {'categories': get_all_categories()} 
       ) 


def cart(request): 
    return render(request, 'cart.html', {'categories': get_all_categories()}) 


def help(request): 
    return render(request, 'help.html', {'categories': get_all_categories()}) 


def about(request): 
    return render(request, 'about.html', {'categories': get_all_categories()}) 


def contact(request): 
    return render(request, 'contact.html', {'categories': get_all_categories()}) 


def search(request): 
    return render(request, 'search.html', {'categories': get_all_categories()}) 


def get_all_categories(): 
    return Category.objects.all() 

這是我cart.html {%伸出 「index.html的」 %}

{% block content %} 

<div> 
<h1> My Cart </h1> 
</div> 

{% endblock %} 

這是什麼contact.html具有 {%延伸 「的index.html」 %}

{% block content %} 

<div> 
<h1> Contact </h1> 
</div> 

{% endblock %} 

Ť他就是home.html的含有 {%伸出「index.html的」%}

{% block content %} 

<div> 
<h1> Home </h1> 
</div> 

{% endblock %} 

這工作,但現在我想知道是否有解決這個讓我沒有更好的方法在所有視圖中重複相同的代碼。

回答

1

您可以編寫自定義context processor以在您渲染的每個模板中包含該變量。

例如,寫一個上下文處理器類似如下(以context_processors.py,說):

def category_context_processor(request): 
    return { 
     'categories': get_all_categories(), 
    } 

,並將其納入settings.py

TEMPLATES = [ 
    ... 
    'OPTIONS': { 
     'context_processors': [ 
      ... 
      'myapp.context_processors.category_context_processor', 
     ], 
    }, 
} 

現在變量categories可在每個模板你渲染(無論如何使用render調用或RequestContext),而不管從視圖中實際傳遞的上下文。

0

您也可以使用模板標籤。

polls/ 
    __init__.py 
    models.py 
    templatetags/ 
     __init__.py 
     poll_extras.py 
    views.py 

在你poll_extras.py的文件

from django import template 

register = template.Library() 

@register.simple_tag 
def get_categories(request, arg1, arg2, ...): 
    return { 
     'categories': get_all_categories(), 
    } 

或者你可以使用有自己的模板使用inclusion_tag(保持相同的所有視圖):

@register.inclusion_tag('categories_block_template.html') 
def get_categories(arg1, arg2, *args, **kwargs): 
    categories = Category.objects.filter(field1=arg1, ...) 
    ... 

最後,在您需要加載templatetag並使用它的模板:

{% load poll_extras %} 

您可以查看關於templatetags的更多信息here

+0

在我看來[Django Classy Tags](https://django-classy-tags.readthedocs.io/en/latest/)是一個優點。 –