2017-02-11 139 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/)是一个优点。 –