问题描述
我是手工艺和树枝的新手,正在尝试访问Neo矩阵内部的表值,并开始遇到一些阻止程序。我不知道如何正确查询值。这是我的代码:
{% if row.tableColumn|length %}
<table>
{% set policyTable = row.tableColumn.all() %}
{{ dump(row.tableColumn.all()) }}
{% for row in policyTable %}
<thead>
<tr>
<th>
{{ row.col1 }}
</th>
</tr>
<tr>
<td>
{{ row.column1 }}
</td>
</tr>
</thead>
{% endfor %}
</table>
{% endif %}
这是转储供参考(缩短):
array(1){[0] => object(craft \ elements \ MatrixBlock)#2695(67) {[“ genericRichTextOnlyListItems”] => NULL [“ tableColumn”] =>字符串(402) “ [{” col1“:” THEAD1“,” col2“:” THEAD2“,” col3“:” THEAD3“,” col4“:” THEAD4“},{” col1“:” ROW1“,” col2“:” 60-75“,” col3“:” 15-30“,” col4“:” 5-20“},{” col1“:” ROW2“,” col2“:” 45-55“,” col3“:” 35-45“,” col4“:” 5-20“},{” col1“:” ROW3“,” col2“:” 5-15“,” col3“:” 75-85“,” col4“:” 15-25“}]” }
我正在尝试访问在工艺后端上已命名为col1
的tableColumn中的column1
。 {{ row.col1 }}
和{{ row.column1 }}
将不起作用。有提示吗?
解决方法
看起来policyTable
是Matrix Blocks的数组。每个数组项(尽管只有一个)在键tableColumn
下都有表格列,因此您可以尝试这样的操作(由于它是数组,因此将policyTable
重命名为policyTables
):
{% if row.tableColumn|length %}
<table>
{% set policyTables = row.tableColumn.all() %}
{% for row in policyTables[0].tableColumn %}
<thead>
<tr>
<th>
{{ row.col1 }}
</th>
</tr>
<tr>
<td>
{{ row.col2 }}
</td>
</tr>
<!-- etc. -->
</thead>
{% endfor %}
</table>
{% endif %}
或者,如果有可能不止一个矩阵块,您可以尝试如下操作:
{% if row.tableColumn|length %}
{% set policyTables = row.tableColumn.all() %}
{% for table in policyTables %}
<table>
{% for row in table.tableColumn %}
<thead>
<tr>
<th>
{{ row.col1 }}
</th>
</tr>
<tr>
<td>
{{ row.col2 }}
</td>
</tr>
<!-- etc. -->
</thead>
{% endfor %}
</table>
{% endfor %}
{% endif %}
在两种情况下,您都可能希望对第一行进行不同的处理,因为它似乎是标题行。您可以为此使用Twig's loop variable。 (可能还有其他方法。)