Rolando
Rolando

Reputation: 62596

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?

Upvotes: 4

Views: 7895

Answers (2)

Ricky Levi
Ricky Levi

Reputation: 7997

I would re-write it with less open/close tags:

% for item in ('apple', 'banana'):
    <%
        isBanana = False
        if item == 'banana':
            isBanana = True
    %>

    % if isBanana:
        <span> Bought a banana</span>
    % endif
% endfor

or

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

It's more readable...

Upvotes: 0

iMom0
iMom0

Reputation: 12921

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

Upvotes: 12

Related Questions