如何将变量传递给django中的所有模板? [重复]

时间:2021-04-21 22:30:27

This question already has an answer here:

这个问题在这里已有答案:

I am trying to pass variables (browser variable) to all my templates in my app. Any advice on how to get it to work?

我试图将变量(浏览器变量)传递给我的应用程序中的所有模板。有关如何使其工作的任何建议?

View:

视图:

def browser(request):
    primary_cat_list = Categories.objects.order_by("category")
    subcat_list = SubCategories.objects.order_by("sub_category")
    product = Productbackup.objects.order_by("website")
    browser =  list(chain(primary_cat_list, subcat_list, product))
    return render_to_response('reserve/templates/base.html', locals(), context_instance=RequestContext(request))

Template:

模板:

{% for prod in browser %} {{ prod }}, {% endfor %}

3 个解决方案

#1


12  

You, my friend, are in the market for Context Processors.

你,我的朋友,在Context Processors市场。

From a blog entry written by a far nimbler and erudite technical writer than I:

来自一个远比我更聪明,更博学的技术作家写的博客文章:

What are template context processors?

什么是模板上下文处理器?

Django’s context processors are a facility that allows you to provide data and callbacks to your templates.

Django的上下文处理器是一种允许您为模板提供数据和回调的工具。

You can do so in one of two ways:

您可以通过以下两种方式之一完成此操作:

  • On an individual request basis: by passing a custom Context value to your render_to_response() call
  • 在单个请求的基础上:通过将自定义Context值传递给render_to_response()调用
  • Globally: by creating a context processor method that accepts a HttpRequest object as input, and returns a payload or callback, then registering the context processor in your settings.py, then providing your render_to_response() call with the built-in RequestContext attribute instead of your own (you can always extend RequestContext to add more data on an individual request basis of course).
  • 全局:通过创建一个接受HttpRequest对象作为输入的上下文处理器方法,并返回有效负载或回调,然后在settings.py中注册上下文处理器,然后使用内置的RequestContext属性提供render_to_response()调用,而不是您自己的(当然,您可以随时扩展RequestContext以在单个请求的基础上添加更多数据)。

If that approach for passing data to templates sounded absurd and obfuscated to you, you’re not alone. The complexity involved in such a simple operation is unwarranted and counter-productive, but every system has its shortcomings.

如果将数据传递给模板的方法对你来说听起来很荒谬和混淆,那么你并不孤单。这种简单操作所涉及的复杂性是没有根据的,适得其反,但每个系统都有其缺点。

The official documentation is here:

官方文档在这里:

https://docs.djangoproject.com/en/dev/ref/templates/api/

https://docs.djangoproject.com/en/dev/ref/templates/api/

So but yeah, I have been programming with Django for a while, and one of the reasons I really like solving problems w/ it is because it is almost Byzantine in its complexity, but not in a domineering sort of way. It has a ton of geegaws and doodads that may not immediately appear useful; each of these either comes in extremely handy when you need it, and it will stay out of your way if not.

所以,但是,我一直在用Django编程一段时间,而且我之所以喜欢解决问题的原因之一是因为它的复杂性几乎是拜占庭式的,而不是一种霸气的方式。它有大量的geegaws和doodads可能不会立即显得有用;当你需要它们时,它们中的每一个都非常方便,如果不是这样的话,它将会不受欢迎。

The upshot here for you is: context processors are a fine example of those. Yes.

这里的结果是:上下文处理器就是这方面的一个很好的例子。是。

#2


4  

Currently you're passing locals() as the variable scope which should include browser aswell, but I find the use of locals() very ugly.

目前你将locals()作为变量范围传递,其中应包括浏览器,但我发现locals()的使用非常难看。

Personally I always prefer a pattern like this instead:

就个人而言,我总是喜欢这样的模式:

def browser(request):
    context = RequestContext(request)

    primary_cat_list = Categories.objects.order_by("category")
    subcat_list = SubCategories.objects.order_by("sub_category")
    product = Productbackup.objects.order_by("website")
    browser =  list(chain(primary_cat_list, subcat_list, product))

    context['browser'] = browser

    return render_to_response('reserve/templates/base.html', context_instance=context)

#3


3  

I can give you an example of my code, that works fine:

我可以给你一个我的代码示例,它可以正常工作:

here is the file named context_processors.py

这是名为context_processors.py的文件

context_processors.py

def base(request):
    user = request.user

#======================
#Login form
#=====================

# here is the code for login user or check if he is logged in already

return  {
        'user': user,
        }

and that's, part of my base.html (a template that I use wor all my pages)

那就是我的base.html的一部分(我使用的所有页面的模板)

base.html

{% if user.username %}
                    <h3>
                        Welcome {{ user.username }}
                    </h3>

#1


12  

You, my friend, are in the market for Context Processors.

你,我的朋友,在Context Processors市场。

From a blog entry written by a far nimbler and erudite technical writer than I:

来自一个远比我更聪明,更博学的技术作家写的博客文章:

What are template context processors?

什么是模板上下文处理器?

Django’s context processors are a facility that allows you to provide data and callbacks to your templates.

Django的上下文处理器是一种允许您为模板提供数据和回调的工具。

You can do so in one of two ways:

您可以通过以下两种方式之一完成此操作:

  • On an individual request basis: by passing a custom Context value to your render_to_response() call
  • 在单个请求的基础上:通过将自定义Context值传递给render_to_response()调用
  • Globally: by creating a context processor method that accepts a HttpRequest object as input, and returns a payload or callback, then registering the context processor in your settings.py, then providing your render_to_response() call with the built-in RequestContext attribute instead of your own (you can always extend RequestContext to add more data on an individual request basis of course).
  • 全局:通过创建一个接受HttpRequest对象作为输入的上下文处理器方法,并返回有效负载或回调,然后在settings.py中注册上下文处理器,然后使用内置的RequestContext属性提供render_to_response()调用,而不是您自己的(当然,您可以随时扩展RequestContext以在单个请求的基础上添加更多数据)。

If that approach for passing data to templates sounded absurd and obfuscated to you, you’re not alone. The complexity involved in such a simple operation is unwarranted and counter-productive, but every system has its shortcomings.

如果将数据传递给模板的方法对你来说听起来很荒谬和混淆,那么你并不孤单。这种简单操作所涉及的复杂性是没有根据的,适得其反,但每个系统都有其缺点。

The official documentation is here:

官方文档在这里:

https://docs.djangoproject.com/en/dev/ref/templates/api/

https://docs.djangoproject.com/en/dev/ref/templates/api/

So but yeah, I have been programming with Django for a while, and one of the reasons I really like solving problems w/ it is because it is almost Byzantine in its complexity, but not in a domineering sort of way. It has a ton of geegaws and doodads that may not immediately appear useful; each of these either comes in extremely handy when you need it, and it will stay out of your way if not.

所以,但是,我一直在用Django编程一段时间,而且我之所以喜欢解决问题的原因之一是因为它的复杂性几乎是拜占庭式的,而不是一种霸气的方式。它有大量的geegaws和doodads可能不会立即显得有用;当你需要它们时,它们中的每一个都非常方便,如果不是这样的话,它将会不受欢迎。

The upshot here for you is: context processors are a fine example of those. Yes.

这里的结果是:上下文处理器就是这方面的一个很好的例子。是。

#2


4  

Currently you're passing locals() as the variable scope which should include browser aswell, but I find the use of locals() very ugly.

目前你将locals()作为变量范围传递,其中应包括浏览器,但我发现locals()的使用非常难看。

Personally I always prefer a pattern like this instead:

就个人而言,我总是喜欢这样的模式:

def browser(request):
    context = RequestContext(request)

    primary_cat_list = Categories.objects.order_by("category")
    subcat_list = SubCategories.objects.order_by("sub_category")
    product = Productbackup.objects.order_by("website")
    browser =  list(chain(primary_cat_list, subcat_list, product))

    context['browser'] = browser

    return render_to_response('reserve/templates/base.html', context_instance=context)

#3


3  

I can give you an example of my code, that works fine:

我可以给你一个我的代码示例,它可以正常工作:

here is the file named context_processors.py

这是名为context_processors.py的文件

context_processors.py

def base(request):
    user = request.user

#======================
#Login form
#=====================

# here is the code for login user or check if he is logged in already

return  {
        'user': user,
        }

and that's, part of my base.html (a template that I use wor all my pages)

那就是我的base.html的一部分(我使用的所有页面的模板)

base.html

{% if user.username %}
                    <h3>
                        Welcome {{ user.username }}
                    </h3>