templates - 如何在tal :attributes using TALES中为同一属性设置多个值

标签 templates chameleon template-tal

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

不幸的是,这不起作用,因为它返回:LanguageError:属性中的属性名称重复。

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

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

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

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

顺便说一句,有没有关于 ChameleonTALES(除了 http://chameleon.repoze.org/docs/latest )的任何好的资源和示例

最佳答案

您可以多次使用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>

这可能会导致类属性为空,但这是无害的。

至于附加文档; Chameleon 是 TAL 的实现,最初是为 Zope 页面模板开发的。因此,您会发现后者的很多文档也适用于 Chameleon,只要您考虑到 Chameleon 的默认 TALES 模式是 python:,而 ZPT 默认为 path : 相反。 Advanced Page Templates chapter例如,Zope Book 的内容也适用于 Chameleon。

关于templates - 如何在tal :attributes using TALES中为同一属性设置多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8044376/

相关文章:

python - zope 的人尝试用 TAL、TALES 和 METAL 解决什么具体问题

html - 将数据存储在 HTML 标记中作为自定义属性

c++ - 嵌套模板类: Parameter default value not accepted

templates - 在 Jekyll 模板中定义 site.title

c++ - 函数模板的多个实例与参数列表匹配

python - 设置 Chameleon 中内联替换的默认值

javascript - 如何将 JSON 插入到 zope chameleon 模板的脚本标签中?

c++ - 如何将非常量 int 作为模板参数传递?

python - Pyramid 和变色龙 ZPT

conditional - 如何有条件地在 TAL (PHPTAL) 中添加 id 属性?