Py学习  »  问与答

[精华] 请教一下,如何统一渲染一个全局变量?

cheng8984 • 10 年前 • 6365 次点击  

初接触django,有些地方不是特别懂,还请大神指教。 我在view里定义了一个webname ,我想让这个webname渲染到所有的模板页面,那么我是不是要render_to_response所有的页面啊?有没有什么高效的方法呢?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/322
 
6365 次点击  
文章 [ 7 ]  |  最新文章 10 年前
cdxfish
Reply   •   1 楼
cdxfish    10 年前

tags or middleware

沃尔德
Reply   •   2 楼
沃尔德    10 年前

1.使用TAG 2.中间件 3.session

cheng8984
Reply   •   3 楼
cheng8984    10 年前

@cheng8984 找到问题了 ,确实是url写的有问题..

    url(r'^bloglist/$', 'blog_list', name='bloglist'),
    url(r'^bloglist/$', 'webconfig',name='webconfig'),

哪个在上面显示哪个

cheng8984
Reply   •   4 楼
cheng8984    10 年前

@Django中国社区 是不是跟url有关系呢?初学不是太懂

Py站长
Reply   •   5 楼
Py站长    10 年前

可以使用context processors来解决全局变量问题 https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors

Writing your own context processors A context processor has a very simple interface: It’s just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

Custom context processors can live anywhere in your code base. All Django cares about is that your custom context processors are pointed-to by your TEMPLATE_CONTEXT_PROCESSORS setting.

Py站长
Reply   •   6 楼
Py站长    10 年前

看不出有啥问题

你要不就试试这种风格看看 return render(request, template_name, ext_ctx)

cheng8984
Reply   •   7 楼
cheng8984    10 年前

我尝试去渲染base.html来达到全局,但是遇到点问题

请教下 webname enter image description here

为什么在模版里不显示呢?

enter image description here

在shell里可以 但是渲染不到模版里 enter image description here