我正在尝试做这样的事情 - 我有一个函数需要包含另一个模板 - 但动态地来自一个变量,我似乎做不到
# 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>
请您参考如下方法:
找到另一个选项。
显然有一个名为 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
