简体   繁体   中英

Render a form ONLY ONCE inside a for loop in a twig template

I have a twig template to display audio options (Auto play and Continuos play) as shown in the screen shot: Click to see the screen shot of the page

The following is the code in my twig file. {{ audio_options_form}} renders the form with the checkboxes.I want to display the check boxes only once if {{ item.audio }} is true. Please let me know what changes should I make:

 <div id="textcontent">
 {% set field = data|slice(2) %}
  {% set field = field|slice(0, -1) %}
<div class="col-md-12">
<div class = "source-box audio">
    {% for item in field %}
     {% if item.audio %}
    {{ audio_options_form }}

      {% if data.play.autoplay == 1 %}
        <audio autoplay controls src= "{{item.audio}}" id = "audio-play">
          Your browser does not support the
          <code>audio</code> element.
        </audio>
      {% elseif data.play.continuousplay == 1 %}
        <audio autoplay controls src= "{{item.audio}}" id = "audio-play" onended="continousPlay('{{data.lastlevel}}')">
          Your browser does not support the
          <code>audio</code> element.
        </audio>
      {% else %}
        <audio controls src= "{{item.audio}}" id = "audio-play">
          Your browser does not support the
          <code>audio</code> element.
        </audio>
      {% endif %}
      <div id="source-controls">
       {# {% if allow_edit == 1 %}
          <a class="edit-text" href="{{ path('heritage_text_manager.editsource', {'sourceid': item.uniqueid}, {'query': {'destination': path('heritage_ui.contentpage', {'textid': textid})}}) }}">{{ 'Edit'|t }}</a>
        {% endif %} #}
        <a class="more use-ajax" data-toggle="modal" data-dialog-type="modal" href="{{ path('heritage_ui.metadata', {'sourceid': item.uniqueid}) }}">{{ 'More'|t }}</a>  
      </div>

    {% endif %}

  {% endfor %}

</div>

Either create a 2nd loop with a flag or use the filter filter .

{% set show_audio_form = false %}
{% for item in field %}
    {% if item.audio %}
        {% set show_audio_form = true %}
    {% endif %}
{% endfor %}
{% if show_audio_form %}{{ audio_options_form  }}{% endif %}
{% for item in field %}
    ... display audio ...
{% endfor %}

{% if items|filter(v => v.audio|default)| length %}
    {{ audio_options_form }}
{% endif %}
{% for item in items %}
    ... display audio ...
{% endfor %}

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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