Search code examples
pythontemplatesmako

Python Mako templating - How can I dynamically decide which def or function to call based on a value in the context?


I would do something like the following in a Mako file:

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

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

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

Basically, I am expecting that the context will contain operations with names "operationOne" and "operationTwo" and I would like to dynamically decide which Mako Def to insert.

In the line ${${operation['name']}Body()} the idea is that in the inner ${} tag ${operation['name']} will resolve to "operationOne", then "operationTwo" and so forth, so then the outer ${} will look like ${operationOneBody()} the first time through the loop and ${operationTwoBody()} the second time through, and so forth -- which will cause the appropriate defs to get called, which will finally fill in the actual content I want in those places.


Solution

  • You can put the functions into a dictionary keyed by the operation names. I think this should do what you want:

    <% 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>