Print this page

Create a ContentArea to simulate a custom AMPScript function

Knowledge Article Number 000213695
Description
If you're trying to create a custom AMPScript function in Marketing Cloud, there's a way to simulate one using ContentAreas, outlined below. 
Resolution
While functions cannot specifically be created in AMPScript, ContentAreas can mimic some of the functionality and reusability of functions. Any variables or parameters used in the ContentArea need to be "static" or "shared" variables.


For example: 

This function accepts an integer and returns a string based on the value of the integer. 


 
public String EvaluateNumber(int number) 
{ 
String str = string.Empty; 
if (number == 10) 
{ 
str = "Number equals ten."; 
} 
else if (number > 10) 
{ 
str = "Number is greater than ten."; 
} 
else 
{ 
str = "Number is less than ten."; 
} 
return str; 
}
 

 

Simulate the function using ContentAreas


1. Set and define the parameter number in the email. 
2. Create a ContentArea entitled "EvaluateNumber" that looks like the below example. 

 
%%[ 
if @number == 10 then 
set @numberEvaluated = "Number equals ten." 
elseif @number > 10 then 
set @numberEvaluated = "Number is greater than ten." 
else 
set @numberEvaluated = "Number is less than ten." 
endif 
]%%
 
3. Initialize the value of the @number variable. 
 
%%[set @number = 20]%%
 
4. Call the ContentArea using the ContentAreaByName function. 
 
%%=ContentAreaByName("my contents\EvaluateNumber")=%%
 
5. To get the value created in the ContentArea, use the @numberEvaluated variable. 
 
%%=v(@numberEvaluated)=%%


The entire HTML of the email looks like the following example where the results would be:
  • 10: Number equals ten. 
  • 20: Number is greater than ten. 
  • 5: Number is less than ten. 
 
<html> 
<body> 
%%[ 
var @number 
set @number = 10 
set @numberEvaluated = '' 
]%% 
%%=ContentAreaByName("my contents\EvaluateNumber")=%% 
%%=v(@number)=%%: %%=v(@numberEvaluated)=%%<br/> 

%%[set @number = 20]%% 
%%=ContentAreaByName("my contents\EvaluateNumber")=%% 
%%=v(@number)=%%: %%=v(@numberEvaluated)=%%<br/> 

%%[set @number = 5]%% 
%%=ContentAreaByName("my contents\EvaluateNumber")=%% 
%%=v(@number)=%%: %%=v(@numberEvaluated)=%%<br/> 
<custom name="opencounter" type="tracking"> 
</body> 
</html


 




promote demote