Выражение tal python с условием

<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>

У меня уже есть класс, который печатает "изображение-N" на основе индекса цикла, но как мне добавить еще один класс, если длина равна "1"? Документация НЕ ясна https://zope.readthedocs.io/en/latest/zopebook/AppendixC.html, в ней говорится, что можно использовать любое допустимое выражение Python, но синтаксис всегда неправильный для меня.

2 ответа

Сам исправил.

                                    <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>

Вы определяете только один внутренний повтор, то есть каждую итерацию - определяете ее снаружи:

    <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>

Но...

ваша задача может (и должна) решаться в CSS3 без дополнительного html-класса:

    .project-images div:first-child:nth-last-child(1) {
         /**/
    }
    .project-images div:only-child {
         /**/
    }
Другие вопросы по тегам