pythonmako

How to set vars in mako template?


I want to be able to do create a variable "hasBannana" exists only within the mako template html that checks for certain things. Assume grocery and and store were passed in from the function that generated the template.

%for customer in store:

hasBannana = false // Invalid syntax
%for item in grocery:

%if item == 'Bannana':
  hasBannana = true  // Invalid syntax
%endif

%if hasBannana: // Invalid syntax
  <span>Bought a Bannana</span>
%endif
%end for

How do I correct this syntax? Is this even possible what I want to do?


Solution

  • Something wrong with your ending %endfor tag, there should be two.

    Code between if tags will be output, <% blah %> then code will be executed.

    % for item in ('apple', 'banana'):
        <%
            isBanana = False
        %>
        % if item == 'banana':
        <%
            isBanana = True
        %>
        %endif
        % if isBanana:
            <span> Bought a banana</span>
        %endif
    %endfor