0

我想<caption>在 StreamField 中为使用 TableBlock 创建的表添加标签,以使表更易于访问且语义正确。现在,默认模板没有那个标签。我不确定我应该如何自定义table.html模板(从默认值开始,如果我为表格块创建自定义类以添加字幕,我不确定如何呈现表格。 <caption>必须是<table>第一个孩子,那就是为什么我需要修改模板。以前有人这样做过吗?

<table>
    <caption>Example Caption</caption> <--- Need this here
    <thead>
        <th>Header col 1</th>
        <th>Header col 2</th>
    </thead>
    <tbody>
    <tr>
        <td>Cell col 1</td>
        <td>Cell col 2</td>
    </tr>
    </tbody>
</table>
4

1 回答 1

0

看看下面的代码。

表块.py

class TableHead(blocks.StructBlock):
    table_head_text = blocks.ListBlock(blocks.CharBlock(max_length=120))

class TableRow(blocks.StructBlock):
    table_row_text = blocks.ListBlock(blocks.CharBlock(max_length=120))

class TableBlock(blocks.StructBlock):
    caption_text = blocks.CharBlock(max_length=120)
    table_head = TableHead()
    table_rows = blocks.ListBlock(TableRow())

    class Meta:
        template = 'wagtail_blocks/table.html'

您会注意到我已经在“元”类中设置了“模板”属性,因此您也必须创建该文件。

表.html

{% load wagtailcore_tags %}

<table>
    <caption>{{ value.caption_text }}</caption>
    <thead>
    {% for header_text in value.table_head.table_head_text %}
        <th>{{ header_text }}</th>
    {% endfor %}
    </thead>
    <tbody>
    {% for table_row in value.table_rows %}
        <tr>
            {% for table_row_text in table_row.table_row_text %}
                <td>{{ table_row_text }}</td>
            {% endfor %}
        </tr>
    {% endfor %}
    </tbody>
</table>

最后,您可以像这样在任何页面中轻松使用新的 TableBlock

body = StreamField([
    ('table', TableBlock()),
])
于 2019-04-18T12:42:20.853 回答