如何使用TALES为tal:attributes中的同一属性设置多个值

rob*_*les 3 templates chameleon template-tal

我正在尝试在一个元素上设置多个css类.

不幸的是,这不起作用,因为它返回: LanguageError: Duplicate attribute name in attributes.

<ul>
    <li tal:repeat="item mainnav"
        tal:attributes="class 'first' if repeat.item.start else nothing; 
                        class 'last' if repeat.item.end else nothing;
                        class 'active' if item.active else nothing">
        <a tal:attributes="href item.href" tal:content="item.title">title</a>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

将这3个案例组合成一个表达式会使其变得非常复杂,因为有6种不同的css状态:

  • 第一个+活跃的
  • 第一
  • 最后+活跃
  • 持续
  • 活性
  • (没有)

我能想到两种可能的解决方案:

- >检查内联的每个组合:

<ul>
    <li tal:repeat="item mainnav" 
        tal:attributes="
            class 'first active' if (repeat.item.start and item.active) else
                  'first'        if repeat.item.start else
                  'last active'  if (repeat.item.end and item.active) else
                  'last'         if repeat.item.end else
                  'active'       if item.active else nothing">
        <a tal:attributes="href item.href" tal:content="item.title">title</a>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

- >创建一个返回组合css类的方法

现在,有没有更好的方法,如果没有,那两个中的哪一个更好(可能是后一个,好像它变得更复杂的内联脚本将变得不可读/无法管理).

顺便说一下Chameleon,有什么好的资源和例子,TALES(http://chameleon.repoze.org/docs/latest除外)

Mar*_*ers 7

您可以tal:define多次使用来定义类字符串的各个部分,然后从这些部分构造实际属性:

<tal:loop repeat="item mainnav">
    <li tal:define="class_first  'first'  if repeat.item.start else '';
                    class_last   'last'   if repeat.item.end else '';
                    class_active 'active' if item.active else '';"
        tal:attributes="class string:$class_first $class_last $class_active">
       <a tal:attributes="href item.href" tal:content="item.title">title</a>
    </li>
</tal>
Run Code Online (Sandbox Code Playgroud)

这可能会导致一个空类属性,这是无害的.

至于其他文件; Chameleon是TAL的一个实现,最初是为Zope页面模板开发的.因此,你会发现后者的很多文档也适用于变色龙,只要你考虑到Chameleon的默认TALES模式是python:,而ZPT默认为path:.例如,Zope Book 的高级页面模板章节也适用于Chameleon.