Django模板上下文功能不自动运行
抱歉,或者标题令人困惑!它实际上比听起来简单得多。
我有一个函数:
def get_messages(request):
# do something expensive with the request
return 'string'
我希望能够从模板调用该函数,所以我绑上了上下文处理器:
def context_processor(request):
return {'messages':get_messages(request)}
所以现在当我的 {{messages}}
template, string
打印出来。伟大的。
问题是 get_messages
非常昂贵并且并不总是需要的。不到一半的模板需要它。有没有一种方法可以将函数传递给模板,然后将其运行或不运行留给模板?
我已经尝试过这个:
def context_processor(request):
return {'messages':get_messages}
但这只是在模板中输出函数描述
而不是运行它。
Sorry or the confusing title! It's actually a lot simpler than it sounds.
I've got a function:
def get_messages(request):
# do something expensive with the request
return 'string'
I want to be able to call that function from the template, so I've strapped in with a context processor:
def context_processor(request):
return {'messages':get_messages(request)}
So now when I have {{messages}}
in my template, string
prints out. Great.
The problem is get_messages
is quite expensive and isn't always needed. Less than half the templates need it. Is there a way of passing the function to the template and leave it up to the template if it runs or not?
I tried this already:
def context_processor(request):
return {'messages':get_messages}
But that just outputs the function description <function get_messages at 0x23e97d0>
in the template instead of running it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你不应该将应用程序的逻辑与模板(MVC 模式中的视图)混合在一起。这破坏了架构的一致性。您可以在需要的视图中调用
get_messages
,并将messages
传递到模板上下文,而在其他视图中只需传递None
即可。但回答你的问题:你可以创建一个代理对象。例如:
您可以使其更加通用,并创建具有一个方法(例如
get
)的 Proxy 类,并在构造函数中采用一个参数:一个将请求对象作为第一个参数的函数。这样您就可以获得通用方法来代理模板中的函数调用。就是这样:那么你可以写得比我之前写的更酷:
I think You shouldn't mix logic of application with template (the view in MVC pattern). This breaks consistency the architecture. You can call
get_messages
in views that need it and simply passmessages
to the template context, in the others just passNone
.But answering Your question: You can make a proxy object. E.g:
You can make this ever more generic, and create Proxy class that has one method (e.g
get
), and takes one parameter in constructor: a function which takes request object as first parameter. This way You gain generic method to proxy a function call in Your templates. Here it is:then You can write even cooler than I had written before: