There are three ways to add AMPscript code to your content: by using inline code, by adding code blocks, or by using tag-based scripting. The first two of these methods use special delimiters to denote the beginning and ending of the code that you want Marketing Cloud Engagement to interpret. In the third method, you delineate the AMPscript code with <script> tags.
When you close an AMPscript block, use the same type of closing delimiter as you used to open the block. For example, if you open a block using tag-based scripting, you can’t close it by using the closing code block delimiter.
Inline AMPscript
Use the %%= and =%% delimiters to add AMPscript code inline with your content. Inline AMPscript is frequently used within HTML tags to dynamically populate the content of a message. In this basic example, a section of AMPscript is included inline within an HTML <p> tag.
1<p>Hello %%= Lowercase(@name) =%%,</p>
You can only execute a single function in a section of inline AMPscript. However, you can nest functions within an inline function. This example uses the Iif() function to test a condition. In this case, the condition is whether the value of the variable @var is empty, which is determined by using the nested Empty() function.
1%%= Iif(Empty(@var),'123','456') =%%
AMPscript Code Blocks
You can also include multi-line blocks of AMPscript code in your messages. Use the %%[ and ]%% delimiters to begin and end a code block, respectively. With a code block, you can define multiple variables and execute multiple functions. Code blocks use the syntax shown in this example.
1%%[2 Var @free_shipping, @country3 Set @country = Uppercase([CountryCode])4 If ( @country == "US" or @country == "CA" ) then5 Set @free_shipping = true6 Else7 Set @free_shipping = false8 EndIf9]%%
AMPscript Tag-Based Syntax
Tag-based syntax for AMPscript standardizes the syntax used to declare AMPscript blocks with the syntax of Server-Side JavaScript (SSJS). This syntax makes it easier for developers to switch between AMPscript and SSJS.
This example shows the complete syntax required to declare an AMPscript block.
1<script runat="server" language="ampscript">2 Var @free_shipping, @country3 Set @country = Uppercase([CountryCode])4 If( @country == "US" or @country == "CA")then5 Set @free_shipping = true6 Else7 Set @free_shipping = false8 EndIf9</script>