【问题标题】:Python Mako templating - How can I dynamically decide which def or function to call based on a value in the context?Python Mako 模板 - 如何根据上下文中的值动态决定调用哪个 def 或函数?
【发布时间】:2012-11-29 13:37:10
【问题描述】:

我会在 Mako 文件中执行以下操作:

%for operation in operation_list:
    ${operation['name']}
    ${${operation['name']}Body()}
%endfor

<%def name="operationOneBody()">
   some stuff
</%def>

<%def name="operationTwoBody()">
   some other stuff
</%def>

基本上,我希望上下文将包含名称为“operationOne”和“operationTwo”的操作,并且我想动态决定插入哪个 Mako Def。

${${operation['name']}Body()} 行中的想法是,在内部 ${} 标记中,${operation['name']} 将解析为“operationOne”,然后是“operationTwo”等等,所以外部 ${} 将看起来像 @987654324 @ 第一次通过循环,${operationTwoBody()} 第二次通过,依此类推——这将导致适当的 defs 被调用,最终将在这些地方填充我想要的实际内容。

【问题讨论】:

    标签: python templates mako


    【解决方案1】:

    您可以将函数放入以操作名称为键的字典中。我认为这应该做你想做的:

    <% operations = { 'one': operationOneBody, 'two': operationTwoBody } %>
    
    %for operation in operation_list:
        ${operation['name']}
        ${operations[operation['name']]()}
    %endfor
    
    <%def name="operationOneBody()">
       some stuff
    </%def>
    
    <%def name="operationTwoBody()">
        some other stuff
    </%def>
    

    【讨论】:

      猜你喜欢
      • 2011-06-12
      • 2017-08-24
      • 1970-01-01
      • 2011-04-29
      • 2013-06-25
      • 2013-04-03
      • 2018-01-03
      • 2010-09-28
      • 1970-01-01
      相关资源
      最近更新 更多