自己动手写垃圾框架 使用mako模板碰到的问题

14 views
Skip to first unread message

shuxiang

unread,
Nov 29, 2009, 8:26:19 PM11/29/09
to pythonbook-comment
自己动手写垃圾框架,使用mako模板
mylookup = TemplateLookup(......................)
mytemplate = mylookup.get_template("foo.html")
print mytemplate.render(arg1=“...”,arg2="...",arg3="...",..........)


这样使用太麻烦,而且要是要传递很多参数到模板更麻烦,我的愿望是:
render(“foo.html”,locals())
于是:
def render(path,namespace):#**kw
mylookup = TemplateLookup(......................)
mytemplate = mylookup.get_template(path)
return mytemplate.render(locals())
但是不能这么使用的mytemplate.render(locals()) ,在老外的讨论区上找到解决,应该改成
return mytemplate.render(**locals())

但是**locals()是什么意思???func(*args,**kwargs)之*args,**kwargs的意思我是懂的,但是这个?---
**locals()


是不是这样-----
**locals()的意思就是把字典分解成 arg1=”..",arg2="...",arg3="..",相当于**kwargs的反转

张沈鹏

unread,
Nov 29, 2009, 9:13:18 PM11/29/09
to pythonboo...@googlegroups.com
locals 就是 返回 当前作用域的所有变量的字典

不过这样传递,往往也会带来名字空间的污染,我个人不是很喜欢

我比较喜欢是的借鉴的pylons的做法,用一个类似c变量的东西来传递参数

比如我的mypy框架中就是这样的


这个G变量就是用来传递参数
@route_render_func
def apply(email=None):
if email:
if auth.is_applyed(email):
G.email_link = email2link(email) or email

if request.is_post:
form = StripJsdict(request.form)
G.error = error = _lib.apply_checker(form)
if not error:
return request.redirect("/auth/apply/%s"%form.email)

页面中这样用
<%def name="htm_body()" filter="trim">
<%
error_tip = ErrorTip(G.error)
form = request.form
%>
%if G.email_link:
<div class="FormTip">
申请成功,激活邮件已发出...
</div>
<p align="center">请到 ${G.email_link|n} 查收激活邮件</p>
## <p align="center">如果没收到邮件,
## <a href="javascript:popwin.load('/auth/popwin/resend_activation/${G.email}');void(0)">点此</a>
重新发送
## </p>
%else:
<form method="POST" class="HideErr Bform Pform" onsubmit="return submit_form()">
<div class="FormTip">
%if error:
<div style="color:#d30">填写有误,请检查...</div>
%else:
<p style="font-size:16px">许多故事,从这里开始...</p>
<p style="font-size:14px;text-align:left;margin-bottom:6px">已有下列网站的账户?点链接,直接登录</p>
<%include file="_openid.htm"/>\
%endif
</div>
<p>注册新账号</p>
<p>
<label>邮箱</label><input autocomplete="off" type="text"
value="${form.email}" class="text" name="email" id="email">
${error_tip.email|n}
<span>输入Email邮箱,接收确认邮件以开始注册。 </span>
</p>


2009/11/30 shuxiang <shuxi...@gmail.com>:

--
卖空间 http://stdyun.com/vhost
写书 http://kanrs.com
豆瓣 http://www.douban.com/people/zuroc
博客 http://zsp.javaeye.com

shuxiang

unread,
Nov 29, 2009, 9:35:57 PM11/29/09
to pythonbook-comment
locals()与globals()的意思当然知道的,我想问的是return mytemplate.render(**locals()) 里的
**locals(),
return mytemplate.render(**locals()) 的作用相当于return mytemplate.render
(arg1="...",arg2="...",......),我只是不明白那两个 ** 的作用。 不过张老大讲的东西非常有用,
locals对名空间的污染其实应该少用。没接触过pylons,对pylons的参数传递还不了解;不过通过老大的例子,感觉那种方法也很方便,没污
染。谢谢张老大的回复

> 2009/11/30 shuxiang <shuxian...@gmail.com>:

张沈鹏

unread,
Nov 29, 2009, 9:44:20 PM11/29/09
to pythonboo...@googlegroups.com
** 就是将字典解包

http://wiki.woodpecker.org.cn/moin/PyAbsolutelyZipManual

4.3. 不定长参数 *para,**para

Reply all
Reply to author
Forward
0 new messages