【发布时间】:2013-06-25 04:46:06
【问题描述】:
我们有这段代码,它运行良好。进行重构后,它不再起作用。就像评论说的那样,如果请求不是 ajax 请求,我们只想从基本页面继承。为此,我们将一个参数传递给模板,并根据该参数,我们是否继承。
查看.py
class Router(object):
def __init__(self, request):
self.request = request
@view_config(route_name="home")
def get(self):
template = "home.mak"
value = {'isPage':self.request.is_xhr is False}
return render_to_response(template, value, request=self.request)
模板.mak
##conditional to determine with the template should inherit from the base page
##it shouldn't inherit from the base page is it is being inserted into the page using ajax
<%!
def inherit(context):
if context.get('isPage') == True:
return "base.mak"
else:
return None
%>
<%inherit file="${inherit(context)}"/>
目前,错误是未定义没有属性__getitem__。如果我们将 ${inherit(context)} 更改为 ${inherit(value)} 我们会得到全局变量值未定义。
【问题讨论】:
-
能不能把所有的逻辑都放到inherit标签里?只是将函数调用排除在等式之外: ${'base.mak' if context.get('isPage') else None}
-
我认为这不是问题所在。我们做了一个相当大的重构,上面的代码又可以工作了。我猜传入的上下文没有初始化,或者其中一个模板存在语法错误。
-
顺便说一句,请求对象有一个名为 is_xhr 的属性,如果请求是异步的,则该属性为 true。我们使用这个属性来确定我们是否需要加载整个页面。所以 is_page = self.request.is_xhr 是 False
标签: python django-templates pyramid mako