Mako 模板中的 Python 函数(不在模块级块中)
我使用 Pyramid 和 Mako 进行模板化。
可以在 Mako 块 <%
和 %>
中定义(半匿名)函数。
我知道可以使用模块级块 <%!
和 %>
来完成,但这意味着我的函数无法访问本地范围在模板化时,这意味着我必须传递我需要的每一位变量。
示例:
...template...
<%
variable_in_local_scope = 'blah blah blah'
def my_function():
header_name = variable_in_local_scope.upper()
return header_name
%>
${foo()}
这将抛出一个 NameError
,表示 header_name
未定义。解决这个问题的唯一方法是将其编码为
<%!
def my_function(input_variable):
return input_variable.upper()
%>
${my_function(variable_in_local_scope)}
This Works,但是当函数有多个变量时,它会变得非常不方便。我还必须在模块级块中重新导入可用于我的模板的任何“帮助程序”函数。
有什么办法可以解决这个问题,还是我在做一些完全愚蠢的事情?
I'm using Pyramid and Mako for templating.
It is possible to define a (semi-anonymous) function within a Mako block <%
and %>
.
I know it can be done with a module-level block <%!
and %>
, but this means my function doesn't have any access to the local scope when templating, meaning I have to pass every bit of variable in that I need.
Example:
...template...
<%
variable_in_local_scope = 'blah blah blah'
def my_function():
header_name = variable_in_local_scope.upper()
return header_name
%>
${foo()}
This will throw a NameError
saying header_name
is not defined. The only way around this has been to code it like
<%!
def my_function(input_variable):
return input_variable.upper()
%>
${my_function(variable_in_local_scope)}
This works, but when there are more than a few variables for the function, it gets quite unweildy. I must also re-import any 'helper' functions available to my template in the module-level-block.
Is there any way around this, or am I doing something completely stupid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:在您的上下文中添加字典,
然后在您的函数中使用它。
注意:Mako 太快了,因为引擎会在渲染之前为每个 *.mak(模板文件)创建一个 python 模块,您可以尝试以下操作:
并检查 '/tmp/mako_modules' 中 *.py 文件的内容
Add a dictionary in your context using:
and then use it in your functions.
Note: Mako is too fast, because the engine will create a python module for each *.mak(template file) before render it, you may try this:
and check content of *.py files in '/tmp/mako_modules'
你尝试过吗:
locals()["header_name"] = ...
did you try:
locals()["header_name"] = ...