简体   繁体   中英

Loop through a HTML code block with different variables

I'm trying to make a loop in order not to rewrite code all the time for an Instagram widget containing 8 photos. Every loop has it's own number (fe theme.instagram_img_1 to theme.instagram_img_8) However there are external variables involved creating a problem in the loop.

{% if theme.instagram_img_1 %}
  <div class="col-12 col-sm-6 col-lg-3 pb30">
    <a href="{{ theme.instagram_url_1 }}">
      <figure>
      <div class="instagram-click"><i class="fa fa-3x fa-instagram"></i></div>
      <img src="{{ 'img-instagram-img-1.jpg' | url_asset }}" width="100%">
      </figure>
    </a>
  </div>
{% endif %}
{% if theme.instagram_img_2 %}
  <div class="col-12 col-sm-6 col-lg-3 pb30">
    <a href="{{ theme.instagram_url_2 }}">
      <figure>
      <div class="instagram-click"><i class="fa fa-3x fa-instagram"></i></div>
      <img src="{{ 'img-instagram-img-2.jpg' | url_asset }}" width="100%">
      </figure>
    </a>
  </div>
{% endif %}

I want the loop to go for 8 times in total. This is what I've come up with so far:

<div id="myHTMLWrapper"></div>

<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
for (var i = 0; i < 8; i++) {
  myHTML += '{% if theme.instagram_img_' + (i + 1) + ' %}<div class="col-12 col-sm-6 col-lg-3 pb30">< a href = "{{ theme.instagram_url_1 }}" ><figure><div class="instagram-click"><i class="fa fa-3x fa-instagram"></i></div><img src="{{ 'img-instagram-img- ' + (i + 1) + '.jpg' | url_asset }}" width="100%"></figure></a></div>{% endif %}';
}
wrapper.innerHTML = myHTML
</script>

In this line has an error:

myHTML += '{% if theme.instagram_img_' + (i + 1) + ' %}<div class="col-12 col-sm-6 col-lg-3 pb30">< a href = "{{ theme.instagram_url_1 }}" ><figure><div class="instagram-click"><i class="fa fa-3x fa-instagram"></i></div><img src="{{ 'img-instagram-img- ' + (i + 1) + '.jpg' | url_asset }}" width="100%"></figure></a></div>{% endif %}';

Change this:

< a href = "{{ theme.instagram_url_1 }}" >

to this:

< a href = "{{ theme.instagram_url_' + (i + 1) + ' }}" >

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