2013/12/20

TAL Expression on Conditional Repeat

TAL (Template Attribute Language) Expressions are used in Zope Page Templates (ZPT) to allow template elements to be replaced, repeated, or omitted. The tal:repeat statement replicates a sub-tree of your document once for each item in a sequence. Here is an example to conditionally repeat and display values based on its value quantity and position.

<div tal:define="choices context/my_field|nothing"
     tal:condition="choices">
  <tal:onlyone condition="python: len(choices) == 1">
  <tal:field i18n:translate="">Primary</tal:field>:
  <span tal:replace="python: view.term_title(choices[0])" />
  </tal:onlyone>
  <tal:many condition="python: len(choices) > 1"
            repeat="choice choices">
    <tal:first condition="repeat/choice/start">
    <tal:field i18n:translate="">Primary</tal:field>:
    <span tal:replace="python: view.term_title(choice)" />
    <br />
    <tal:field i18n:translate="">Secondary</tal:field>:
    </tal:first>
    <tal:others condition="not:repeat/choice/start">
    <span tal:replace="python: view.term_title(choice)" />
    <span class="separator" tal:condition="not: repeat/choice/end">,</span>
    </tal:others>
  </tal:many>
</div>

Another common usage is to test a variable before inserting it (the first example tests for existence and truth, while the second only tests for existence):

<p tal:condition="request/message | nothing"
   tal:content="request/message">message goes here</p>

<p tal:condition="exists:request/message"
   tal:content="request/message">message goes here</p>

No comments: