首页 > 解决方案 > 使用 craftcms 的 Twig 表问题

问题描述

我是手工艺和树枝的新手,我正在尝试访问新矩阵中的表值,并开始遇到一些障碍。我不知道如何正确查询我认为的值。这是我的代码:

{% 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]=> 对象(craft\elements\MatrixBlock)#2695 (67) {["genericRichTextOnlyListItems"]=> NULL ["tableColumn"]=> string(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 }}

标签: twigcontent-management-systemcraftcms

解决方案


看起来像是一个矩阵块policyTable数组。每个数组项(虽然只有一个)在 key 下都有表列,所以你可以尝试这样的事情(我重命名为,因为它是一个数组):tableColumnpolicyTablepolicyTables

{% 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 的循环变量。(可能还有其他一些方法。)


推荐阅读