Removing multiple code sections using a variable

Today we are gonna look at a special scenario.

If the user does not upload an image, we want to remove the red and blue squares on both sides.

The code looks somewhat like this

<table width="100%" cellspacing="0" cellpadding="0" border="0">
  <tr>
<!-- LEFT SIDE WITH IMAGE -->
    <td style="width:50%;>
      <img alt="" src="{{ design.global_settings.header_image.url }}" style="style="width:310px; display: block; border: 0; height: 316px;" />
    </td>
<!-- LEFT SIDE WITH IMAGE -->

<!-- HEADER -->
    <td align="center" style="vertical-align:top;">
      <table class="w-90p alpaco-bg" cellspacing="0" cellpadding="0" border="0" style="width:350px;">
        <tr>
          <td align="center">
            How do you like the editor?
          </td>
        </tr>
      </table>
    </td>
<!-- HEADER -->

<!-- RIGHT SIDE -->
    <td class="hide" style="width:50%;">
      <img alt="" src="https://alpaco-uploads.s3.eu-central-1.amazonaws.com/1/605d7a47-10e6-4211-819d-f207954ea675/74727563-f803-4bce-bfa1-41b2cc0a816f.png" height="316" style="width:310px; display: block; border: 0; height: 316px;" />
    </td>
<!-- RIGHT SIDE -->
  </tr>
</table>

Instead of creating a boolean switch, we can make a variable that detects, if there was uploaded an image. Here we assign our variable showTD that is equal to our image, image.url and looks if the image.url is empty.

 {% assign showTDs = design.global_settings.header_image and design.global_settings.header_image.url and design.global_settings.header_image.url != '' %}

Afterwards we can wrap our td's inside the new variable.

{% if showTDs %}<br><td>Left side</td><br>{% endif %}

<td>How do you like the editor?</td><br>

{% if showTDs %}<td>Right side</td>{% endif %}

If you made it this far, you are awesome!

Last updated