Reference - Macro methods
Macro expressions allow you to use a large variety of methods. The following categories list the methods according to the type of provided functionality:
- Data manipulation
- Data conversion
- Text manipulation
- Advanced text processing
- Date and time modification
- Mathematical operations
- E-commerce
- User membership and permissions
- Transformations
Keep in mind that the recommended macro syntax is to use infix notation for the first parameter of methods.
For example: {% “word”.ToUpper() %} instead of {% ToUpper(“word”) %}
Data manipulation
Method |
Return type |
Parameters |
Description |
GetValue |
object |
|
Gets the value of the specified data column of an object that implements the ISimpleDataContainer interface. You can specify a default value used if the requested data is null. Example: {% CurrentDocument.GetValue(“NewsTitle”) %} |
GetProperty |
object |
|
Gets the value of the specified property of an IHierarchicalObject object. You can specify a default value used if the requested property is null. Example: {% CurrentDocument.GetProperty(“NewsTitle”) %} |
GetItem |
object |
|
Gets the object at the specified index of a collection. You can specify a default value used if the requested object is null. Example: {% GlobalObjects.Users.GetItem(0).UserName %} |
OrderBy |
IInfoObjectCollection |
|
Returns the collection of objects, with the order defined by the specified SQL ORDER BY clause. If the macro is saved by a user without the Administrator privilege level, the method only allows the following SQL syntax:
Example: {% GlobalObjects.Users.OrderBy(“UserCreated DESC”).FirstItem.UserName %} |
Where |
IInfoObjectCollection |
|
Filters a collection of objects according to the specified SQL Where condition. If the macro is saved by a user without the Administrator privilege level, the method only allows the following SQL syntax in the where condition:
Other expressions and SQL functions are not supported. Example: {% GlobalObjects.Users.Where(“Email LIKE ‘%@localhost.local’”).FirstItem.UserName %} |
TopN |
IInfoObjectCollection |
|
Returns only the specified number of objects in the collection. Example: {% GlobalObjects.Users.TopN(1).FirstItem.UserName %} |
Columns |
IInfoObjectCollection |
|
Returns the collection of objects containing only the specified data columns. If the macro is saved by a user without the Administrator privilege level, the method only allows the following SQL syntax:
Example: {% GlobalObjects.Users.Columns(“UserName, Email”).FirstItem.UserName %} |
Filter |
IList |
|
Filters a collection of objects according to the specified macro condition. Example: {% GlobalObjects.Users.Filter(UserID == 53).FirstItem.UserName %} |
ClassNames |
TreeNodeCollection |
|
Filters a TreeNodeCollection of pages according to the specified page types. The second parameter must contain a list of allowed page type code names, separated by semicolons. Example: {% Documents.ClassNames(“cms.menuitem;cms.news”).Count %} |
InList |
bool |
|
Returns a true value if the object exists within the specified collection. Example: {% CurrentDocument.ClassName.InList(“cms.menuitem,cms.root”.Split(“,”)) %} |
All |
bool |
|
Returns a true value if all of the objects in the collection match the given condition. Specify the condition as a macro expression. Example: {% GlobalObjects.Users.All(UserEnabled == true) %} |
Any |
bool |
|
Returns a true value if at least one object in the collection matches the given condition. Specify the condition as a macro expression. If you leave out the condition parameter, the method returns true if the collection contains at least one object. Throws an exception if the collection is null. Example: {% GlobalObjects.Users.Any(UserEnabled == false) %} |
Exists |
bool |
|
Returns a true value if at least one object in the collection matches the given condition. Specify the condition as a macro expression. If you leave out the condition parameter, the method returns true if the collection contains at least one object. Returns false if the collection is null. Example: {% GlobalObjects.Users.Exists(UserEnabled == false) %} |
RandomSelection |
IList |
|
Returns randomly selected objects from the collection. You can optionally specify the number of items. Example: {% GlobalObjects.Users.RandomSelection().UserName %} |
SelectInterval |
IList |
|
Returns the specified interval of objects from the collection. Example: {% Documents.SelectInterval(0,9) %} |
Cache |
object |
|
Evaluates the specified macro expressions and stores the result in the server-side application cache. The system only evaluates the expression if the result is not found in the cache. See also: Caching the results of macros |
GetCacheDependency |
CMSCacheDependency |
|
Returns a CMSCacheDependency object based on the specified dummy cache keys (one or more string parameters). See also: |
> Back to the list of macro method categories
Data conversion
Method |
Return type |
Parameters |
Description |
ToString |
string |
|
Converts an object to a string. Returns the optional default value if the conversion is not possible. You can also specify the culture context and a formatting string used for the conversion. Examples:
|
ToInt |
int |
|
Converts an object to an integer number. Returns the optional default value if the conversion is not possible. Example: {% DocumentID.ToInt() %} |
ToBool |
bool |
|
Converts an object to a boolean value. Returns the optional default value if the conversion is not possible. Example: {% DocumentShowInSiteMap.ToBool() %} |
ToDecimal |
decimal |
|
Converts an object to a decimal number. Returns the optional default value if the conversion is not possible. You can also specify a culture code to determine the formatting of the decimal number. Examples:
|
ToDouble |
double |
|
Converts an object to a double number. Returns the optional default value if the conversion is not possible. You can also specify a culture code to determine the formatting of the double number. Examples:
|
ToGuid |
guid |
|
Converts an object to a GUID value. Returns the optional default value if the conversion is not possible. Example: {% DocumentGUID.ToGuid() %} |
ToDateTime |
DateTime |
|
Converts an object to a DateTime value. Returns the optional default value if the conversion is not possible. You can also specify a culture code to determine the date format. Example: {% ToDateTime(”12/31/2017 11:59 PM”) %} |
FromOADate |
DateTime |
|
Converts a double representation of a date and time value (OLE Automation Date) to a DateTime object. Example: {% FromOADate(43100.999305556) %} |
ToTimeSpan |
TimeSpan |
|
Converts an object to a TimeSpan value. Returns null if the conversion is not possible. Example: {% ToTimeSpan(“1:00:00”) %} |
ToBaseInfo |
BaseInfo |
|
Converts an object to a BaseInfo — the general type for Kentico system objects and pages. Returns the optional default value if the conversion is not possible. Example: {% CurrentUser.ToBaseInfo() %} |
List |
ArrayList |
|
Converts a list of objects to an ArrayList. Example: {% List(“Apple”, “Orange”, “Banana”) %} |
> Back to the list of macro method categories
Text manipulation
Method |
Return type |
Parameters |
Description |
Contains |
bool |
|
Returns a true value if the string specified by the second parameter occurs within the first string. |
EndsWith |
bool |
|
Indicates whether the string specified by the second parameter occurs at the end of the first string. |
Format |
string |
|
Replaces all formatting expressions in a string using the text equivalents specified in the second parameter. Based on composite formatting. |
FormatNotEmpty |
string |
|
If the first parameter is not empty or null, replaces all formatting expressions in the string using the text equivalents specified in the second parameter. Returns the optional third parameter if the value is null or empty. Based on composite formatting. |
GetMatch |
string |
|
Matches the string value to the specified regular expression and returns the match. |
IndexOf |
int |
|
Returns the index of the first occurrence of the second string within the first string. |
LastIndexOf |
int |
|
Returns the index of the last occurrence of the second string within the first string. |
LimitLength |
string |
|
Limits the length of the string to the specified number of characters. The padString parameter allows you to set a string that the method appends to the end of the limited result. The length of the parameter is included in the maximum length. If you set the wholeWords parameter to true, the method preserves the last word in the string. |
LoremIpsum |
string |
|
Generates lorem Ipsum text. You can specify the number of generated characters (1000 by default). |
Matches |
bool |
|
Indicates whether the string matches the specified regular expression. |
NotContains |
bool |
|
Returns a true value if the string specified by the second parameter does NOT occur within the first string. |
PadLeft |
string |
|
Adds leading characters to the string until the total length matches the second parameter. By default, the method uses spaces as the padding character, but you can optionally specify a different character. |
PadRight |
string |
|
Adds trailing characters to the string until the total length matches the second parameter. By default, the method uses spaces as the padding character, but you can optionally specify a different character. |
RegexReplace |
string |
|
Replaces strings that match the regular expression pattern within the first string using the replacement string. |
Remove |
string |
|
Deletes characters from the string, starting at the specified index. By default, the method removes all remaining characters from the specified position. You can optionally specify the number of characters to be removed. |
Replace |
string |
|
Replaces all occurrences of the second string within the first string using the replacement string. |
Split |
string[] |
|
Separates the string into an array of substrings according to the specified delimiting characters. If the optional third parameter is true, the method removes empty substrings from the result. |
StartsWith |
bool |
|
Indicates whether the string specified by the second parameter occurs at the start of the first string. |
Substring |
string |
|
Returns a substring starting at the specified index. By default, the method returns all remaining characters from the specified index. You can optionally specify the number of characters to be returned. |
ToLower |
string |
|
Converts the entire string to lower case. |
ToUpper |
string |
|
Converts the entire string to upper case. |
Trim |
string |
|
Removes all leading and trailing occurrences of characters from the string. By default, the method trims white space characters, but you can optionally specify a different set of characters (as a string). |
TrimEnd |
string |
|
Removes all trailing occurrences of characters from the string. By default, the method trims white space characters, but you can optionally specify a different set of characters (as a string). |
TrimStart |
string |
|
Removes all leading occurrences of characters from the string. By default, the method trims white space characters, but you can optionally specify a different set of characters (as a string). |
Tips: To perform lexicographical comparison of strings, use the basic comparison operators (==, <, >, <=, >=). Add macro parameters to specify case sensitivity and the culture context of text operations.
> Back to the list of macro method categories
Advanced text processing
Method |
Return type |
Parameters |
Description |
GetResourceString |
string |
|
Translates the specified resource (localization) string. By default, the target language of the localization depends on the current culture. You can specify the target language using the optional parameter. |
JSEscape |
string |
|
Escapes the string for safe usage in JavaScript. Adds the \ escape character before special characters used by JavaScript (quotes, etc.). Note: The JSEscape method is not available when resolving macros in an external application using the Kentico.Libraries NuGet package. |
Localize |
string |
|
Resolves localization expressions within the specified text. By default, the target language of the localization depends on the current culture. You can specify the target language using the optional parameter. |
MapPath |
string |
|
Returns the physical file path that matches the specified virtual path. |
ResolveBBCode |
string |
|
Resolves BBCode tags in the specified text, for example: {% ResolveBBCode(“[quote]Sample text[/quote]”) %}. |
ResolveMacroExpressions |
string |
|
Resolves the specified macro expression (without the {% %} parentheses). |
ResolveMacros |
string |
|
Resolves all macros within the specified text. |
ResolveUrl |
string |
|
Converts relative URLs starting with ~/ to relative URLs containing the current application path (so they can be resolved by clients). Absolute URLs remain unchanged. |
StripTags |
string |
|
Removes all HTML tags from the specified text. |
SQLEscape |
string |
|
Escapes the string for safe usage in SQL commands (to avoid SQL injection). |
UnresolveUrl |
string |
|
Converts relative URLs containing the application path to relative URLs starting with ~/. Absolute URLs remain unchanged. |
UrlEncode |
string |
|
Applies URL encoding to the specified string. |
> Back to the list of macro method categories
Date and time modification
Method |
Return type |
Parameters |
Description |
AddMilliseconds |
DateTime |
|
Adds the specified number of milliseconds to a DateTime value. |
AddSeconds |
DateTime |
|
Adds the specified number of seconds to a DateTime value. |
AddMinutes |
DateTime |
|
Adds the specified number of minutes to a DateTime value. |
AddHours |
DateTime |
|
Adds the specified number of hours to a DateTime value. |
AddDays |
DateTime |
|
Adds the specified number of days to a DateTime value. |
AddWeeks |
DateTime |
|
Adds the specified number of weeks to a DateTime value. |
AddMonths |
DateTime |
|
Adds the specified number of months to a DateTime value. |
AddYears |
DateTime |
|
Adds the specified number of years to a DateTime value. |
ToShortDateString |
string |
|
Converts the value of the DateTime parameter to an equivalent short date string representation. |
ToShortTimeString |
string |
|
Converts the value of the DateTime parameter to an equivalent short time string representation. |
> Back to the list of macro method categories
Mathematical operations
The macro autocomplete help only shows the mathematical methods as members of the Math namespace, for example {% Math.Abs(-2) %}. However, the system resolves the methods even without the namespace.
Method |
Return type |
Parameters |
Description |
Abs |
double |
|
The absolute value of the specified number. |
Acos |
double |
|
The angle whose cosine is the specified number. |
Asin |
double |
|
The angle whose sine is the specified number. |
Atan |
double |
|
The angle whose tangent is the specified number. |
Average |
double |
|
The average of all numbers in the specified data column of the objects in the collection. |
Ceiling |
double |
|
The smallest whole number greater than or equal to the specified number. |
Cos |
double |
|
The cosine of the specified angle. |
Cosh |
double |
|
The hyperbolic cosine of the specified angle. |
Exp |
double |
|
e raised to the specified power. |
Floor |
double |
|
The largest whole number lesser than or equal to the specified number. |
GetRandomInt |
int |
|
Generates a random positive integer. You can use the optional parameters to specify the range of possible numbers, and the seed number for the generator. |
GetRandomDouble |
double |
|
Generates a random positive decimal number. You can use the optional parameters to specify the range of possible numbers, and the seed number for the generator. |
IsOdd |
bool |
|
Returns a true value if the specified number is odd. |
IsEven |
bool |
|
Returns a true value if the specified number is even. |
Log |
double |
|
The base e logarithm of a specified number. |
Log10 |
double |
|
The base 10 logarithm of a specified number. |
Max |
double |
|
The maximum from the given list of numbers. |
Maximum |
double |
|
The maximum of all numbers in the specified data column of the objects in the collection. |
Min |
double |
|
The minimum from the given list of numbers. |
Minimum |
|
The minimum of all numbers in the specified data column of the objects in the collection. |
|
Modulo |
int |
|
The modulo of two integer numbers. |
Pow |
double |
|
The number raised to the specified power. |
Percent |
double |
|
Multiples the specified number by 0.01. |
Round |
double |
|
The number nearest to the specified value. The optional second parameter sets the number of fractional digits in the rounded value. You can use the third parameter to set the rounding mode for numbers half-way between two other numbers. Supported variants are:
|
Sign |
double |
|
Returns a value indicating the sign of a number:
|
Sin |
double |
|
The sine of the specified angle. |
Sinh |
double |
|
The hyperbolic sine of the specified angle. |
Sqrt |
double |
|
The square root of a specified number. |
Sum |
double |
|
The sum of all numbers in the specified data column of the objects in the collection. |
Tan |
double |
|
The tangent of the specified angle. |
Tanh |
double |
|
The hyperbolic tangent of the specified angle. |
> Back to the list of macro method categories
E-commerce
Basic product methods
Method |
Return type |
Parameters |
Description |
GetSKUPrice |
string |
|
Returns the price of the specified product (object skuId). The price includes any catalog discounts that apply. Example: {% FormatPrice(GetSKUPrice(SKUID), true) %} |
GetSKUOriginalPrice |
string |
|
Returns the greater of the following price options for the specified product (object skuId):
If both prices are equal to the standard product price with discounts (i.e. the product’s list price is equal to the price and no discounts apply), the method returns 0. The price is in the current user’s shopping cart currency. Example: {% FormatPrice(GetSKUOriginalPrice(SKUID), true) %} |
GetSKUPriceSaving |
string |
|
Returns the amount of money saved on the price of the specified product (object skuId). The savings are calculated based on the difference between the product’s price (from the SKUPrice column, including any catalog discounts that apply) and the greater of the following options:
If the product’s price is greater than the list price and no discounts apply, the method returns 0. The result is in the current user’s shopping cart currency. Example: {% GetSKUPriceSaving(SKUID) %} |
GetSKUTax |
string |
|
Depending on the site’s Prices include tax setting, returns either:
For example:
Example: {% FormatPrice(GetSKUTax(SKUID), false) %} |
IsOptionUsedInVariants |
bool |
|
Returns true if the product option with the specified ID (int skuID) is used in any existing product variant. |
Related methods
Method |
Return type |
Parameters |
Description |
GetFormattedWeight |
string |
|
Returns formatted weight (double weight) based on the mass unit format configuration in the settings. |
GetManufacturer |
object |
|
Returns an object from the specified column (string column) of the manufacturer with the specified ID (int id). |
GetDepartment |
object |
|
Returns an object from the specified column (string column) of the department with the specified ID (int id* ). |
GetSupplier |
object |
|
Returns an object from the specified column (string column) of the supplier with the specified ID (int id* ). |
GetInternalStatus |
object |
|
Returns an object from the specified column (string column) of the internal status with the specified ID (int id* ). |
GetPublicStatus |
object |
|
Returns an object from the specified column (string column) of the public status with the specified ID (int id* ). |
GetMainSiteCurrency |
CurrencyInfo |
|
Returns the currency used on the site with the specified ID (int siteID). |
GetShoppingCartItemsCount |
int |
Returns the number of products in the current shopping cart. |
|
GetCouponsMessage |
string |
|
Returns an information message about the redemption count of coupon codes belonging to the specified discount (object Discount). |
GetMultiBuyCouponsMessage |
string |
|
Returns an information message about the redemption count of coupon codes belonging to the specified Buy X Get Y discount or Product coupon (object MultiBuyDiscount). |
GetGiftCardCouponsMessage |
string |
|
Returns an information message containing the total redeemed and remaining amount for all coupon codes belonging to the specified Gift card (object GiftCard). The amount values are in the site’s main currency. |
GetMassUnit |
string |
Returns the mass unit of the Kentico instance. |
|
FormatPrice |
string |
|
Returns the price (decimal price) formatted according to the currency used by the current shopping cart. The optional parameter determines whether the price is rounded based on the current site’s settings (bool round). |
FormatPriceForCart |
string |
|
Returns the price (decimal price) formatted according to the currency used by the specified shopping cart (int cartID). The optional parameter determines whether the price is rounded based on the settings of the shopping cart’s site (bool round). |
FormatPriceInMainCurrency |
string |
|
Returns the price (decimal price) formatted according to the current site’s main currency. The optional parameter determines whether the price is rounded based on the current site’s settings (bool round). |
ShoppingCartProducts |
IEnumerable |
|
Returns the products (shopping cart items) in the specified shopping cart (object cartGUID). Bundle items and product options are excluded from the list. |
URLs
Method |
Return type |
Parameters |
Description |
GetAddToWishListLink |
string |
|
Returns a HTML link (<a> tag) with a URL that adds the specified product (object productId) to the current user’s wishlist. Additionally, an image is rendered before the link tag (using the ~/CMSModules/CMS_Ecommerce/addtowishlist.png file). |
GetRemoveFromWishListLink |
string |
|
Returns the URL for removing the specified product (object productId) from the current user’s wishlist. |
ShoppingCartURL |
string |
|
Returns the URL of the current user’s shopping cart set up in the checkout process settings on the specified site (string siteName). You can specify a shopping cart’s GUID (object cartGUID), which is added to the URL’s query string, to restore products in the shopping cart (for example, when sending an email reminder of an abandoned shopping cart). |
WishlistURL |
string |
|
Returns the URL of the current user’s wishlist on the specified site (string siteName). |
GetProductUrl |
string |
|
Returns the URL of the product specified by the identifier (object SKUID), which is the primary key. |
GetProductUrlForFeed |
string |
|
Returns the URL of the specified product (object skuGUID) with the specified name (object skuName) with the feed query string parameter in the URL for the feed on the specified site (object siteName). |
GetEproductUrl |
string |
|
Returns the URL for downloading an e-product specified with a unique download URL (Guid fileToken), a file name (string fileName), and an ID of the site on which the order with the e-product took place (int siteId). |
GetProductUrlByGUID |
string |
|
Returns the user-friendly URL of the product specified by the GUID (object skuGuid) and name (object skuName) of the product. You can specify the site name of the product’s site (object siteName). |
GetProductImage |
string |
|
Returns the complete HTML code of the URL of the specified product image (object imageURL) on the current site with the alternative text (object alt). You can specify the maximum width (object maxSideSize), or the required width (object width) and height (object height). |
GetAddToShoppingCartLink |
string |
|
Note: This method is obsolete, and only works if the site’s shopping cart page (specified by the Shopping cart URL setting) contains the Checkout process (obsolete) web part. Returns a HTML link (<a> tag) with a URL that adds the specified product (object productId) to the current user’s shopping cart. Use the optional enabled parameter if you wish to dynamically set whether the method returns the link (based on the status of individual products). Additionally, an image is rendered before the link tag (using the ~/CMSModules/CMS_Ecommerce/addorder.png file). |
Google tag manager e-commerce data
Method |
Return type |
Parameters |
Description |
GetGtmProductJson |
string |
|
Returns a JSON string containing the data of a specified product (int skuId), in a format suitable for use with the Google Tag Manager and Universal Analytics Enhanced Ecommerce features. For more information, see Integrating Google Analytics Enhanced Ecommerce. The optional additionalDataJson parameter allows you to extend the returned JSON string (custom fields and values). The optional purpose parameter can be processed in code customizations of the product data creation process, if you need to return different JSON data for various scenarios. Example: {% GetGtmProductJson(SKUID), “{ ‘list’ : ‘Search Results’}”, “searchImpressions”) %} |
GetGtmPurchaseJson |
string |
|
Returns a JSON string containing the data of a completed order (purchase), in a format suitable for use with the Google Tag Manager and Universal Analytics Enhanced Ecommerce features. Only works on the page that you display to customers after they go through your website’s checkout process (the page specified by the Final step URL property of your site’s Page wizard manager web part, typically a payment page or “thank you” page). For more information, see Integrating Google Analytics Enhanced Ecommerce. The optional additionalDataJson parameter allows you to extend the returned JSON string (custom fields and values). The optional purpose parameter can be processed in code customizations of the purchase data creation process, if you need to return different JSON data for various scenarios. |
GetGtmShoppingCartItemsJson |
string |
|
Returns a JSON string containing the data of all products in the current shopping cart, in a format suitable for use with the Google Tag Manager and Universal Analytics Enhanced Ecommerce features. For more information, see Integrating Google Analytics Enhanced Ecommerce. The optional additionalDataJson parameter allows you to extend the returned JSON string (custom fields and values). The optional purpose parameter can be processed in code customizations of the product data creation process, if you need to return different JSON data for various scenarios. |
> Back to the list of macro method categories
User membership and permissions
Method |
Return type |
Parameters |
Description |
CheckPrivilegeLevel |
bool |
|
Checks the user’s privilege level. Returns a true value if the user’s privilege level matches the required UserPrivilegeLevelEnum value or is higher. You can check the following levels:
|
GetFormattedUserName |
string |
|
Returns the formatted username of the specified user object. The default format is <full name> (<nickname>) if the user has a nickname, otherwise <full name> (<username>). The isLiveSite parameter determines whether the macro displays the username on the live website. |
HasAnyMembership |
bool |
|
Checks whether the user belongs to any membership in the system. |
HasMembership |
bool |
|
Checks if a user belongs to the specified memberships. Enter the code names of memberships through the userMemberships parameter. When checking multiple memberships, use semicolons (;) to separate the code names. If the allMemberships parameter is true, the user must belong to all specified memberships for the check to succeed. To check whether the user belongs to a membership on a global level, add the period character (.) prefix before the membership code name. |
IsAuthorizedPerResource |
bool |
|
Evaluates whether a user has a specific permission for a resource (module). Use code names to identify the resource and permission. |
IsAuthorizedPerUIElement |
bool |
|
Evaluates whether a user is allowed to access a specific UI element of a resource (module). Use code names to identify the resource and element. |
IsInGroup |
bool |
|
Checks if a user belongs to a group (community or workgroup). |
IsInRole |
bool |
|
Checks if a user belongs to the specified roles. Enter the code names of roles through the userRole parameter. When checking multiple roles, use semicolons (;) to separate the code names. If the allRoles parameter is true, the user must belong to all specified roles for the check to succeed. To check whether the user belongs to a role on a global level, add the period character (.) prefix before the role code name. |
> Back to the list of macro method categories
Transformations
Method |
Return type |
Parameters |
Description |
ApplyTransformation |
string |
|
Applies Text / XML transformations to a collection of items. |
Transform |
string |
|
Applies ad-hoc transformation code (Text / XML type) to a collection of items, or a single item. Note: To keep the macro syntax valid, you need to break all %} closing macro tags within the ad-hoc transformation code into separate strings. Example: {% CurrentUser.Transform(“<strong>{%FullName%” + “}</strong>”) %} |
When writing Text / XML transformations, you can use most ASCX transformation methods inside macro expressions.
Outside of transformations, the macro autocomplete only offers the methods under the Transformation namespace, for example Transformation.GetDocumentUrl(). However, you can manually enter the methods even without the namespace.