Search code examples
pythonchameleontemplate-tal

Chameleon template looping


I tried to create template using chameleon. Here is a code snipet.

Calling module runtemp.py:

delete_list=[]
delete={'Name':'aaa','Sirname':'bbb','Friends':['ccc','ddd','eee']}
delete_list.append(delete)
templates = PageTemplateLoader(os.path.join(path, "templates"))
template = templates["delete_user.pt"]
print template(tdelete_list=delete_list)

Template file delete_list.pt:

 <?xml version="1.0" encoding="UTF-8"?>
 <Delete>
   <DeleteRequest>

       <DeleteItems tal:repeat="deletions tdelete_list">

           <Deleteuser tal:repeat="delete repeat.deletions" >

                <Name tal:content="repeat.delete.Name"></Name>
                <Sirname tal:content="repeat.delete.Sirname"></Sirname>
                 <Friends>
                      <Friend tal:repeat="friend repeat.delete.Friends">
                               <Value tal:content="friend"></Value>
                       </Friend>
                 </Friends>

           </Deleteuser>

     <DeleteItems>

    </DeleteRequest>

 </Delete>

Output i got:

 <Delete>
        <DeleteRequest>

           <DeleteItems>



           </DeleteItems>
  </DeleteRequest>
 </Delete>

My problem is the middle tags are not getting printed; what is wrong?


Solution

  • The line <DeleteItems tal:repeat="deletions tdelete_list"> means to loop over tdelete_list and put each element in the variable deletions.

    Thus, your inner loop just needs to loop over deletions; the repeat. prefix is not used here:

    <Deleteuser tal:repeat="delete deletions" >
    
        <Name tal:content="delete.Name"></Name>
        <Sirname tal:content="delete.Sirname"></Sirname>
         <Friends>
              <Friend tal:repeat="friend delete.Friends">
                       <Value tal:content="friend"></Value>
               </Friend>
         </Friends>
    
    </Deleteuser>
    

    The repeat.deletions variable is actually only used to store loop metadata; the current count, the first and last flags, the odd and even flags, etc.