简体   繁体   English

将树枝中模板文件的输出连接起来以循环到变量?

[英]Concatenate output from template file inside twig for loop to variable?

I have a situation where I need to include a template file inside another template and output it in a for loop. 我有一种情况,我需要在另一个模板中include一个模板文件,并在for循环中将其输出。 The problem I am having though, is that it's outputting to a container and I only need the container to render once, but I need the included template to render on all iterations of the loop. 我遇到的问题是,它正在输出到容器中,我只需要容器渲染一次,但是我需要包含的模板在循环的所有迭代中渲染。

{% for details in array %}

  {% set data_details %}
    {{ include('data.html.twig') }}
  {% endset %}

  <!-- Other HTML needed in the loop -->

  {% if loop.first %}
    <tr class="table-row">
      <td>
        {{ data_details | raw }}
      </td>
    </tr>
  {% endif %}

{% endfor %}

As you can see, the {% if loop.first %} prevents the container from repeating. 如您所见, {% if loop.first %}防止容器重复。 But I need data.html.twig to loop on every iteration and append the HTML to the data_details variable but the variable only contains the last iteration. 但是我需要data.html.twig在每次迭代中循环,并将HTML附加到data_details变量中,但该变量仅包含最后一次迭代。 I am not that knowledgeable with Twig so maybe I am going about this the wrong way. 我对Twig不太了解,所以也许我会以错误的方式来做。 The documentation says if you wrap something in a set it will "capture" the output but that isn't happening for some reason. 该文档说,如果将某些东西包装在set ,它将“捕获”输出,但是由于某种原因没有发生。

You're close, the iteration does overwrite the already set variable. 您已经很接近了,迭代确实会覆盖已经设置的变量。 To append to the already set variable , you can repeat/output the variable in the wrap to recapture/concatenate it 要追加到已经设置的变量上,可以在包装中重复/输出该变量以重新捕获/连接它

  {% set data_details %}
    {{ data_details | default('') }}
    {{ include('data.html.twig') }}
  {% endset %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM