Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - Django - How to make a variable available to all templates?

I would like to know how to pass a variable to all my templates, without repeating the same code on every method in my views.py file?

In the example below I would like to make categories (an array of category objects) available to all templates in the web app.

Eg: I would like to avoid writing 'categories':categories on every method. Is it possible?

One view method

def front_page(request):
    categories = Category.objects.all()
    if is_logged_in(request) is False:
        return render_to_response('users/signup.html', {'is_logged_in': is_logged_in(request), 'categories':categories}, context_instance=RequestContext(request))
    else:
        return render_to_response('users/front_page.html', {'is_logged_in': is_logged_in(request), 'categories':categories},context_instance=RequestContext(request))

Another view method

def another_view_method(request):
    categories = Category.objects.all()
    return render_to_response('eg/front_page.html', {'is_logged_in': is_logged_in(request), 'categories':categories},context_instance=RequestContext(request))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want is a context processor, and it's very easy to create one. Assuming you have an app named custom_app, follow the next steps:

  • Add custom_app to INSTALLED_APPS in settings.py (you've done it already, right?);
  • Create a context_processors.py into custom_app folder;
  • Add the following code to that new file:

    def categories_processor(request):
     categories = Category.objects.all()            
     return {'categories': categories}
    
  • Add context_processors.py to TEMPLATE_CONTEXT_PROCESSORS in settings.py

    TEMPLATE_CONTEXT_PROCESSORS += ("custom_app.context_processors.categories_processor", )
    

And now you can use {{categories}} in all the templates :D

As of Django 1.8

To add a TEMPLATE_CONTEXT_PROCESSORS, in the settings you must add the next code:

TEMPLATES[0]['OPTIONS']['context_processors'].append("custom_app.context_processors.categories_processor")

Or include that string directly in the OPTIONS.context_processors key in your TEMPLATES setting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...