pythontemplatescherrypymako

Calling json inside Mako Template without for loops


im trying to figure out how to call something from a json file without using for loops.

% for projekte in liste:
        <tr>
            <td>${projekte['id']}</td>
            <td>${projekte['projektnummer']}</td>
            <td>${projekte['bezeichnung']}</td>
            <td>${projekte['beschreibung']}</td>
            <td>${projekte['bearbeitungszeitraumA']} bis ${projekte['bearbeitungszeitraumB']}</td>
            <td>${projekte['budget']}</td>
            <td>${projekte['kundenverweis']}</td>
            <td>${projekte['mitarbeiterverweis']}</td>
            <td>${projekte['aufwand']}</td>
            <td>
                <ul class="buttons">
                    <li><a href="edit?key=${projekte['id']}">Bearbeiten</a></li>
                    <li><a href="delete?key=${projekte['id']}">Löschen</a></li>
                    % for orga in liste3:
                        <li><a href="/orga/edit?key=${orga['id']}">${orga['bezeichnung']}</a></li>
                    % endfor
                </ul>
            </td>
        </tr>
    % endfor

orga has id's of the projects. The issue is that i cant figure out how to inluce them without a loop because this one will give me a link for every project i have inside very single entry. I want it to send me to another form with the projects ID to continue there.


Solution

  • Why not going through its keys ?

    % for projekte in liste:
       <%
        # instead of looping on `liste3` variable until you find the match
        # extract the match directly.
        # if not found - value is None by default
        orga = liste3.get(projekte['id'])
       %>
       <tr>      
          % for key, value in projekte.items():
            <td> ${value} </td>
    
            % if orga:
            <li>
                <a href="/orga/edit?key=${orga['id']}">
                    ${orga['bezeichnung']}
                </a>
            </li>
            % endif
    
          % endfor
       </tr>
    %endfor
    

    A side note regarding the <td>s: The for key,value can be replaced with the following if you care about the order of the rows/values

    sort_by = ['id', 'projektnummer', 'bezeichnung' ...]
    
    % for key in sort_by:
       <td> ${projekte[key]} </td>
    % endfor
    

    OR, if you care about the order, make sure to initialize projekte as projekte = OrderedDict() vs projekte = {} it will keep its order during insertion of values / keys ... also when printing ...