|
|
AMPscript Syntax GuideFrom $1Table of contents
(Click the banner to go to the related Docs.Code.ExactTarget.com page.) This document contains conceptual and procedural information on AMPscript syntax and usage, including function calls, variables, values, and keywords. You can use the information in this document to correctly form AMPscript function calls, declare variables and values, and reference AMPscript keywords. Using AMPscript Code and FunctionsYou call the AMPscript at the location in the email message, landing page, or SMS message where you want the result of the script to appear. All AMPscript code and functions must be surrounded by open and close delimiters, or the code will be ignored by the system. %%[script]%% Function Call Outside an AMPscript Block (Inline AMPscript)Function calls outside of an AMPscript block must be introduced by the opening delimiter %%= and terminated by the closing delimiter =%%. %%=LOWERCASE(Name)=%%
%%=UPSERTDE("ent.CustomObject4",2,"Region","None","Product",_SubscriberKey,"Available",0,
"Price",100.77,"Inventory",0,"ExpireDate",NOW(),"Url",CONCAT(SubscriberID," Upsert"))=%%
The inline AMPscript example below demonstrates how to include multiple AMPscript references inside a single set of delimiters: <a href="%%=RedirectTo(TreatAsContent(Concat(view_email_url,"&ep=20110902&oeid=20110902",Substring(Uppercase(Source),1,1))))=%%"> Function Call Inside an AMPscript Block Function calls within an AMPscript block should not include the opening (%%=) and closing (=%%) delimiters. %%[ LOWERCASE(Name) ]%% Function Return ValuesFunction output can also be referenced in script and function calls. In the case of functions, this is implemented through nested function calls. For example: %%=LOWERCASE(SUBSTRING(Name, 1, 5))=%% Tag-based Syntax for AMPscriptTag-based syntax for AMPscript standardizes the syntax used to declare AMPscript blocks with the syntax of server-side JavaScript. This syntax eases the burden on developers to write in a different syntax when switching between AMPscript and server-side JavaScript. Use the information below to format your AMPscript calls. The system processes AMPscript calls in a case-insensitive manner. Minimum SyntaxThis sample illustrates the minimum syntax necessary to declare an AMPscript block. <script runat=server language=ampscript>
[INSERT AMPSCRIPT HERE]
</script>
Full SyntaxThis sample illustrates the complete syntax used to declare an AMPscript block. <script runat=server language="ampscript" executioncontexttype="Post" executioncontextname=test>
[INSERT AMPSCRIPT HERE]
</script>
The AMPscript block must be closed in the same syntax that opens it. For example, if you open a block using <script>, you must close it with </script> and not ]%%. Delimiter ComparisonThe table below demonstrates the similarities between standard AMPscript delimiters and server-side delimiters.
Using Function CallsYou can use ExactTarget function calls inside AMPscript blocks or outside of script blocks: anywhere a traditional substitution string is valid. Function calls outside of AMPscript blocks must be introduced by the opening delimiter %%= and terminated by the closing delimiter =%%. Function calls within AMPscript should not include these delimiters. These function calls will be executed even if they are not part of a scripting statement, such as SET or IF. Function Call Outside an AMPscript Block %%=LOWERCASE(Name)=%% Function Call Inside an AMPscript Block %%[ LOWERCASE(Name) ]%% Functions Accept Any of These Input Types: Constant Value LOWERCASE("Mary Smith")
Attribute Value LOWERCASE(Name) Variable Value LOWERCASE(@Name) AMPscript Language ElementsAMPscript uses the following language elements:
ConstantsAMPscript can include numeric constants and string constants. Numeric constant values consist of an unquoted set of numerals and can also include one decimal point and an introductory minus sign to indicate negative values. Numeric constant values cannot contain commas. Here are some examples:
String (or text) constant values must be quoted in double or single quotes. String constants can escape the delimiting quote character if they appear within the text by doubling it. Alternative quote characters, such as smart quotes, are not recognized.
Boolean constant values must be true or false and are case insensitive. Here are some examples:
Attribute and Data Extension (Custom Object) ValuesSubscriber attribute, additional email attributes, and data extension column values are referenced in functions and scripts as unquoted strings. If the attribute, data extension column, table, or relationship name includes a space or special character, it must be enclosed in square brackets. For example:
You can define additional email attributes within the email and use them in substitutions or as parameters in AMPscript function calls. ExactTarget must enable the use of additional email attributes for you account. Contact your ExactTarget representative with any questions about this functionality. KeywordsVariables can be declared, initialized, and modified within a script. Variables then can be referenced by script statements and functions. A variable declaration consists of the keyword VAR followed by one or more comma-delimited variable names. Variable names must begin with the @ symbol and be followed by at least one other letter, number, or underscore. Spaces and commas are not allowed in variable names. For example: @Name @C1 A variable assignment consists of the keyword SET followed by the variable name, equal sign, and value.
Declaring a variable with the VAR keyword adds an entry to the Variables Dictionary with the variable name as the key and NULL as the value. If an entry for that name already exists, the value of the variable is set to NULL. If the variable is being used to control a FOR loop, an attempt to declare it will result in a validation or runtime error. %%[VAR @Count]%% %%[VAR @Count1, @Count2, @Count3]%% Using Conditions SyntaxUse the following syntax for simple comparison: <variable, attribute><simple operator><variable, attribute, function, constant> Comparison operators compare values.
Join operators are used to combine multiple conditions.
The NOT operator reverses the result of any Boolean expression.
You can control the expression evaluation using parentheses:
Using IF Syntaxif <condition> then <statement>
elseif <condition> then <statement>
.
else <statement>
endif
Statements
Using the IF Condition EvaluationThe IF statement allows the conditional execution of any content within the IF block dependent on the evaluation of the logic expressions it contains. IF statements may be nested within IF statements. The syntax for the IF statement follows: %%[IF expression1 <comparison operator> expression2 THEN]%%
[wrapped script or email content]
%%[ELSEIF expression1 <comparison operator> expression3 THEN]%%
[wrapped script or email content]
%%[ELSE]%%
[wrapped script or email content]
%%[ENDIF]%%
The ELSEIF statement is optional and can be repeated as desired to evaluate additional conditions. The ELSE statement is optional and can appear only once after the IF and all ELSEIF statements and before the ENDIF to define default behavior if none of the preceding conditions evaluate True. Multiple conditions can be used for an IF or ELSEIF statement. These must be joined by the AND or OR keywords and can be grouped by parentheses to control the order of evaluation. The NOT keyword can be used to reverse the evaluation: IF expression1 <comparison operator> expression2
AND [NOT] (expression3 <comparison operator> expression4
OR expression3 <comparison operator> expression5)
THEN .
Expressions can include any of the input types, including constants, variables, attributes/data extension values, or function calls. If the comparison operator and second expression are not included, an equal operator is assumed with a comparison value of True. IF NOT EMPTY(expression1) THEN The following example demonstrates how to include a variable if a value is present and leave that variable out if no value is present: %%[if not empty(MailingAddress) then]%% %%MailingAddress%% %%[endif]%% Using the FOR Process LoopThe FOR statement allows content within the FOR block to be iterated over a variable number of times. The syntax of the FOR loop follows: %%[FOR @Variable = <start expression> TO|DOWNTO <end expression> DO ]%%
[wrapped script or email content]
%%[NEXT @Variable]%%
The @Variable is a variable that will be locked from modification within the process loop. The start and end index expressions can be any one of the four types of input that evaluates to an integer-a numeric constant, an attribute or data extension value, a variable, or a function call-for example, LookupRows(). The NEXT statement closes the FOR loop and can optionally be followed by the variable name that is controlling the loop. Using the SET StatementVariables are assigned a value using the SET statement. Only one variable may be initialized using a SET statement. An attempt to set a variable that is in use at the counter of a FOR loop will generate a validation or runtime error. The variable takes on the type of the assigned value. %%[ VAR @Count, @Count2 SET @Count = 0 SET @Count2 = 100 ]%% @Name @C1 Using the Output and OutputLine keywordsThe keywords Output and OutputLine returns the results of code executed inside a code block and includes the results in the rendered content. The OutputLine keyword also appends a carriage return and line feed (CRLF) to the end of the resolved content. Output and OutputLine works with the results of a nested function or script block, and they do not support the passing of direct literals. Given the code below: %%[Output(Now())]%% The system prints the current date and time. The OutputLine keyword would return the same information with a CRLF appended at the end. Given the code below: %%[ Var @text Set @text = "Example Text" Output(v(@text)) ]%% The system prints "Example Text," as that text is the value of the variable @text. Note that the code in the example below DOES NOT WORK: %%[ Var @text Set @text = "Example Text" Output(@text) ]%% Again, the code example above does not work because Output does not support the passing of direct literals. Given the function below: %%[ OutputLine(Substring("Example Text",1,6)) ]%%
System prints "Exampl", as the Substring() function shown returns the first 6 characters in the text starting with the first character, and it appends a CRLF at the end of the results. Using CommentsAMPscript may contain comments-or non-executed notes-that allow you, as the author, to document your code. You must open comments with the /* sequence and close comments with the */ sequence. Comments may span multiple lines. %%[ /* Insert Comment Here */ ]% Using AMPscript Language Elements with Enterprise AwarenessThe following AMPscript functions have Enterprise awareness:
You can use the ENT. prefix with these functions to indicate to the system that the data extension being operated on exists at the parent Enterprise level and not at the child level. In the following example, the system looks up data from the MERCHANT data extension stored at the Enterprise Administrator level: %%[
Var @rows
Set @rows = LookupRows("Ent.Merchants","TRAVELWEB_MERCHANT_ID",200043800)
]%%<br>
%%=Field(Row(@rows,1),"merchant_name")=%%<br><br>
Using Data Modification FunctionsTwo sets of functions allow a client's data extension data to be modified through AMPscript: send time support and landing page support. These functions allow insert, update, upsert (update/insert), and delete actions to be performed at the subscriber level. The use of these functions is restricted according to the content being processed by the ExactTarget system. The key or filter fields for update and upsert calls are distinguished from the columns being set by the second parameter for these calls. This parameter must have a value of 1 or more to indicate how many of the following column name and column value pairs make up the key for finding the row to be updated. The remaining name and value pairs specify the columns to be updated and the new values. %%=UPDATEDE("DE_To_Update",1,"Filter Column","Filter Value","Column","Value")=%%
Send Time SupportIf an error occurs, the subscriber emails for the batch will not be sent and the job will be set to an error status. If the sending of the batch is interrupted, these calls for the interrupted batch maybe repeated. You should therefore write these calls in a manner that will allow them to be successfully executed multiple times. The calls are executed only when they appear in the preferred email type of the subscriber. Therefore, if a multi-part message is being built for a subscriber with an HTML email preference, the functions in the text email body will not be executed even though it is built. In the same way, if a subscriber has a text email preference, only the functions in the text version of the email will be processed. A _SourceDE substitution string is provided to reference the source data extension for a send so that the name does not have to be hard-coded. Example%%=INSERTDE("CustomObject4","Region","None","Product",_SubscriberKey,"Price",99.77, "Inventory", 88,
"ExpireDate",NOW(),"Available",1,"Inventory",77,"Locale", LOOKUP("CustomObject3",
"Custom Object Value"
,"Region",Region),"_FromName","Bob",<"_FromEmail",LOOKUP("CustomObject2","EmailAddress",
"Region1",Region))=%% %%=UPDATEDE("CustomObject4",1,"Region","None","Available",0,"Price",100.77,"Inventory",0,
"ExpireDate",NOW())=%% %%=UPDATEDE(_SourceDE,1,"_CustomObjectKey",_CustomObjectKey,"Total & Credit - Cost",_CustomObjectKey,"SubscriberID",SubscriberID)=%% %%=UPSERTDE("ent.CustomObject4",2,"Region","None","Product",_SubscriberKey,"Available",0, "Price",100.77,"Inventory",0,"ExpireDate",NOW(),"Url",CONCAT(SubscriberID," Upsert"))=%% %%=DELETEDE("CustomObject4","Region","None")=%%
Landing Page SupportThe INSERTDATA, UPDATEDATA, UPSERTDATA, and DELETEDATA functions allow data extension data to be modified when building landing pages. This functionality is distinguished from the send time functions in the following ways:
If the INSERTDE, UPDATEDE, UPSERTDE, or DELETEDE counterparts appear in landing page content, they will be executed in the same manner, except they will not return the number of rows affected. They will not be executed in a single batch in this context. Example%%=INSERTDATA("CustomObject4","Region","None","Product",_SubscriberKey,"Price",99.77, "Inventory", 88,
"ExpireDate",NOW(),"Available",1,"Inventory",77,"Locale",LOOKUP("CustomObject3","Custom Object Value","Region",Region),"_FromName","Bob","_FromEmail",LOOKUP("CustomObject2",
"EmailAddress","Region1",Region))=%%
%%=UPDATEDATA("CustomObject4",1,"Region","None","Available",0,"Price",100.77,"Inventory",
0,"ExpireDate",NOW())=%%
%%=UPSERTDATA("ent.CustomObject4",2,"Region","None","Product",_SubscriberKey,"Available",
0,"Price",100.77,"Inventory",0,
"ExpireDate",NOW(),"Url",CONCAT(SubscriberID," Upsert"))=%%
%%=DELETEDATA("CustomObject4","Region","None")=%%
Using Execution ContextContent used in landing pages, Web Collect and Smart Capture and called via an AMPScript function can be processed contextually by the ExactTarget system. That message content is processed depending on the context of the function's execution. Execution context is supported by type and name and represented by the global read-only variable @@ExecCtx. The system processes Load and Post types, and it defaults to Load if no context is specified in the call. Any content without a specific execution context will always be processed. The system honors any context type, and it only processes script blocks in the active content with the specified name. For example, the ExactTarget system processes only script blocks named SaveData if the caller specifies the Post context type and the blocks are located in a section of code executed for the Post type. The caller sets @@ExecCtx to a string value of Load or Post, indicating the current execution context, and the value is case-insensitive. Use this variable to to control the processing of content according to execution context as shown in the example below: /* Content and Script to always be executed here */
%%[ IF @@ExecCtx == "LOAD" THEN]%%
%%[/*Load Content or Script Here*/]%%
%%[ ELSEIF @@ExecCtx == "POST" THEN]%%
%%[/*Load Content or Script Here*/]%%
%%[ENDIF]%%
/* Content and Script to always be executed here */
You can also control processing of content using execution context names. When the caller specifies a name, only script blocks with that name are executed. Callers can also specify a script type at the script block level, with the script name and type set immediately after the script start delimiter. Use single or double quotes for the string values. Names and types are case insensitive: %%[[name="nameStr";type="Load|Post].]%%
In this example, the UpsertData command executes only if the caller's execution context is set to POST and the name UpdateDate is specified:
%%[[name="UpdateDate";type=" Post]UpsertData("MyDE","Col1",Val1,"Col2",Val2)]%%
Script blocks must be completed within the same script block section. For example, any IF or FOR statements inside a script block must be completed by an ENDIF or NEXT within the same named script block. If script blocks span two or more script block sections, the ExactTarget returns the following error message: "An incomplete IF statement exists in a typed script block. Script statements cannot span named or typed script blocks." You can also use execution context to determine whether to display most current content or the content current as of when the email was sent. This document provides an example of how to use AMPscript to contextually display send-time content, which requires enabling the send logging feature. Using Dynamic Link NamesDynamic link names or link aliases are supported. This functionality lets you include dynamic content, including substitution strings and AMPscript function calls, in the name assigned to a link and then track the link by the resolved values. This functionality is available only if:
When creating an email, include your dynamic statements when setting the link name or alias attribute in the Content Editor inside the user interface. For example: <a href="http://website.example.com/key/p...ID=C12915x001B" target="new" alias="%%=CONCAT(Region,' Region')=%%"> This example tracks the link specified above separately by each subscriber's region included in the send. For example: West Region North Region. There is a configuration limit on the number of unique resolved link names, as defined by a link alias, that can be tracked for each link with a dynamic link name. This limit is 100 names. If the number of unique link names exceeds this limit, the excess links are tracked under the original unresolved link name. Date and Time FormattingYou can use several different data and time formats with AMPscript, depending on your needs. The table below demonstrates the available formats:
For example, the AMPscript below takes the results of the DateAdd() function (using the examples from the table) and returns it in the specified format: %%=Format(Now(), "MMMM d, yyyy")=%% August 15, 2011 The example below takes the value of Now(), offsets it using the DateAdd() function, then returns that value in the specified format: %%[ VAR @futureDate, @today SET @today = Now(1) SET @futureDate = DateAdd(@today, 11, "D") ]%% Date: %%=Format(@futureDate, "MMMM d, yyyy")=%% The example below outputs the Birthday attribute of a subscriber in the format specified: %%[Output(Format([Birthday],"dd/MM/yyyy"))]%% AMPscript Syntax TemplatesYou can use the files linked below to highlight AMPscript functions and variables within the Notepad++ and Ultraedit text editors. These templates also support code folding for IF statements and AMPscript blocks. To use these templates, download the .zip files and install the templates using the instructions found on the readme.txt files. ExactTarget does not offer support for these files. Appendix A: Alphabetical List of AMPscript FunctionsThis is an alphabetized list of all AMPscript functions documented in these pages.
This page was last updated by Ryan Williams on Tue, 17 Jan 2012 16:59:42 GMT. If you require assistance with the ExactTarget application, please contact Global Support. If you wish to send Ryan direct feedback, fill out the form below:
Tags: (Edit tags)
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Powered by MindTouch 2010 |