How to Show Conditional HTML Content with AMPscript

When migrating an email from Responsys to SFMC, there was a need to show table cells conditionally based on subscriber data. The original code had if statements wrapped around opening <td> cells, and within <td> cells. Attempting to replicate this approach with AMPscript failed; the AMPscript IF ELSE code got moved inside the content block when switching between Preview and Content views.

<#if module.position.value == "left">
    <td style="text-align: center; padding-top: 10px; width: 140px;" width="140">
<#else>
    <td style="width: 140px;" width="140">
</#if>
<#if module.position.value == "left">
    <table>Content here</table>
</#if>
</td>

The AMPscript solution was to:

  • Wrap whole td cells inside each IF statement.
  • Add HTML comments around the AMPscript to stop the code from shifting within the content block. AMPscript within HTML comments will still render.
<!--%%[IF @position !== "left" THEN]%%-->
<td style="width: 140px;" width="140"></td>
<!--%%[ENDIF]%%-->

<!--%%[IF @position == "left" THEN]%%-->
<td style="text-align: center; padding-top: 10px; width: 140px;" width="140">
    <table>Content here</table>
</td>
<!--%%[ENDIF]%%-->