You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django嵌套for循环中创建唯一ARIA标签的合规实现方案

Django嵌套循环中ARIA标签差异化合规方案

给你几个直接可行的合规方案,不用搞隐藏元素这类临时hack:

  • 利用循环计数器拼接唯一标签
    Django的for循环自带forloop.counter(当前循环序号)、forloop.parentloop(外层循环对象)这些变量,直接用它们和基础文本拼接,就能生成唯一的ARIA标签,还能体现层级关系。
    示例代码:

    {% for item in items %}
      <section class="media" aria-label="媒体项 {{ forloop.counter }}">
        {% for detail in item.details %}
          <section class="media-body" aria-label="媒体项 {{ forloop.parentloop.counter }} - 详情 {{ forloop.counter }}">
            <!-- 内容区域 -->
          </section>
        {% endfor %}
      </section>
    {% endfor %}
    
  • 用模型唯一标识+语义文本生成标签
    如果你的模型有唯一ID(比如item.id)或者有语义化的字段(标题、副标题等),直接用这些内容构建标签,比计数器更稳定(排序变化也不会乱),同时标签更有实际意义。
    示例代码:

    {% for item in items %}
      <section class="media" aria-label="媒体内容:{{ item.title }}">
        {% for detail in item.details %}
          <section class="media-body" aria-label="媒体内容:{{ item.title }} - 详情:{{ detail.subtitle }}">
            <!-- 内容区域 -->
          </section>
        {% endfor %}
      </section>
    {% endfor %}
    
  • 用aria-describedby关联从属内容
    如果media-body是media的补充说明内容,没必要给它单独设aria-label,直接用aria-describedby关联到media的唯一ID即可,既合规又简洁。
    示例代码:

    {% for item in items %}
      <section class="media" id="media-{{ item.id }}" aria-label="媒体内容:{{ item.title }}">
        {% for detail in item.details %}
          <section class="media-body" aria-describedby="media-{{ item.id }}">
            <!-- 内容区域 -->
          </section>
        {% endfor %}
      </section>
    {% endfor %}
    

这些方案都完全符合无障碍规范的“唯一标签”要求,没有用任何临时hack手段,而且标签语义清晰,对屏幕阅读器用户友好。

内容的提问来源于stack exchange,提问作者CodeGorilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:52:25