Django 上下文中 context.push() 和 context.update() 有什么区别
What is the difference between context.push() and context.update() in Django Context
从文档中,我了解到上下文对象是一个堆栈。那么 push()
和 update()
对这个代码段做了什么?文档中指出 push()
和 update()
相似,但 update()
以字典作为参数。那我们为什么要在这里同时使用它们?
import django.template
import django.template.loader
def render(name, *values):
ctx = django.template.Context()
for d in values:
ctx.push()
ctx.update(d)
t = django.template.loader.get_template(name)
return str(t.render(ctx))
此外,将上下文对象作为堆栈有什么需要?
编辑:我再次浏览了文档,发现 flatten()
函数可以展平堆栈中的所有级别,使它们具有可比性。
唯一的区别似乎是(也根据 tests)将参数传递到调用中的方式。更新采用字典,而推送采用关键字参数。
关于有用性,文档说:
Using a Context as a stack comes in handy in some custom template
tags.
从文档中,我了解到上下文对象是一个堆栈。那么 push()
和 update()
对这个代码段做了什么?文档中指出 push()
和 update()
相似,但 update()
以字典作为参数。那我们为什么要在这里同时使用它们?
import django.template
import django.template.loader
def render(name, *values):
ctx = django.template.Context()
for d in values:
ctx.push()
ctx.update(d)
t = django.template.loader.get_template(name)
return str(t.render(ctx))
此外,将上下文对象作为堆栈有什么需要?
编辑:我再次浏览了文档,发现 flatten()
函数可以展平堆栈中的所有级别,使它们具有可比性。
唯一的区别似乎是(也根据 tests)将参数传递到调用中的方式。更新采用字典,而推送采用关键字参数。
关于有用性,文档说:
Using a Context as a stack comes in handy in some custom template tags.