tal python expression with condition

349 views Asked by At
<tal:block tal:repeat="image project/images">
    <div 
        tal:define="onlyone python:if repeat.image.length==1: return 'onlyone'"
        tal:attributes="class python:'image-{}'.format(repeat.image.number)">
        <img 
            tal:define="img image/getObject" 
            tal:replace="structure img/@@images/image/custom_1280" 
        />
    </div>
</tal:block>

I already have a class the prints "image-N" based on the loop index, but how do I add another class if the length is "1"? The documentation is NOT clear https://zope.readthedocs.io/en/latest/zopebook/AppendixC.html#tales-python-expressions, it says any valid python expression can be used but the syntax is always wrong for me.

2

There are 2 answers

0
Sandro Antonucci On

Fixed it myself.

                                    <tal:block tal:repeat="image project/images">
                                        <div 
                                            tal:define="onlyone python:'onlyone' if repeat.image.length == 1 else ''"
                                            tal:attributes="class string:image-${repeat/image/number} ${onlyone}">
                                            <img 
                                              tal:define="img image/getObject" 
                                              tal:replace="structure img/@@images/image/custom_1280" 
                                            />
                                        </div>
                                    </tal:block>
0
Dek4nice On

You define onlyone inside repeat, i.e. every iteration - define it outside:

    <div class="project-images"
        tal:define="onlyone python: len(project.images)==1 and 'onlyone' or '';">
        <tal:project-images repeat="image project/images">
            <div tal:attributes="class string:image-${repeat/image/number} ${onlyone};">
                <img
                    tal:define="img image/getObject" 
                    tal:replace="structure img/@@images/image/custom_1280" 
                />
            </div>
        </tal:project-images>
    </div>

But...

your task can (and should) be solved in CSS3 without additional html class:

    .project-images div:first-child:nth-last-child(1) {
         /**/
    }
    .project-images div:only-child {
         /**/
    }