我正在尝试做这样的事情 - 我有一个需要包含另一个模板的函数 - 但是动态来自变量我似乎无法做到这一点
# include template A
add_tmpl("a.html")
# include template B
add_tmpl("b.html")
<%def name="add_tmpl(include_file)">
<%inherit file="${include_file}" /> # doesn't work
<%include file="${include_file}" /> # work but I need to define args=""
<%/def>
调试时的错误列表:
# NameError: global name 'include_file' is not defined
<%inherit file="${include_file}" />
# mako.exceptions.SyntaxException: Expected: %> in file 'templates/index.html' at line: 220 char: 9
<%inherit file=${include_file} /> # and same for:
<%inherit file=include_file />
# Can't find template ( thought maybe it will know it's a variable )
<%inherit file="include_file" />
这是我用完想法的地方......任何想法?
我写这篇文章,直到我得到其他人的真实解决方案/答案。
由于问题出在我include
vs inherit
的时候 - 我还需要动态定义args=""
- 但每次使用add_tmpl()
函数都有不同的变量(在Mako的后续版本中你不需要,但我无法升级)。
作为临时解决方案,我做过类似的事情:
# include template A
add_tmpl("a.html", var1=value1, var2=value2, var3=value2)
# include template B
add_tmpl("b.html", var3=value3)
<%def name="add_tmpl(include_file, include_args)">
<%include file="${include_file}" args="**include_args" />
<%/def>
答案 0 :(得分:1)
找到另一个选择。
上面有一个名为context
的变量,它中包含kwargs
。
因此,我们只需编写**context.kwargs
即可提取当前模板中的所有变量并按原样传递
我们可以使用
将所有变量传递给包含的模板<%include file="${include_file}" args="**context.kwargs" />
<%include file="${include_file}" args="var1=var1, **context.kwargs" />
有关它的更多信息:http://docs.makotemplates.org/en/latest/runtime.html#mako.runtime.Context