Dynamic Content (DC)

Dynamic Content (DC) allows you to use a scripting language (JavaScript) to change the content of each message. Using DC, you will be able to show different content to different users depending on the conditions selected. You can also use DK to insert system or user variables.

Instructions on how to work with the scripting language

System variables

The personalisation tag is formed from the system name of the field, taken in double curly braces

{{dc:fieldname_example}}

The table lists the system variables that can be used in dynamic content expressions

Main fields

Tag Description Example
{{subscriber_email}} contact email [email protected]
{{subscriber_phone}} contact phone number +71234567899
{{subscriber_firstname}} contact's name (as it is written in the field) Vasily
{{subscriber_firstname_capitalized}} contact name, brought to the standard form - the first capital, the rest lowercase Ekaterina (even if the value in the field is ekaterina)
{{subscriber_lastname}} contact's surname (as it is written in the field) Turkin
{{subscriber_lastname_capitalized}} contact's surname reduced to standard form - first capitalised, the rest lowercase Ivanova (even if in the field is Ivanova)
{{subscriber_name}} contact's first and last name (combines subscriber_firstname and subscriber_lastname) Vasily Turkin
{{subscriber_email_md5}} email in MD5 hash format b58996c504c5638798eb6b511e6f49af
{{subscriber_email_sha256}} SHA256 hash of email 0xC1059ED8
{{subscriber_id}} unique contact ID 123
{{group_names}} names of GRs to which the contact has subscribed, only works in DOI emails Newsletters

System links

Tag Description
{{link_unsubscribe}} unsubscribe from all mailing groups at once in one click
{{link_unsubscribe_manager}} unsubscribe manager
{{link_view_in_browser}} web version of the letter
{{link_confirm}} subscription confirmation link in the confirmation email

Date the letter was sent

Tag Description Example
{{message_day}} number of message sending 11
{{message_dayofweek}} day of the week of sending the message Friday
{{message_shortdate}} summary date of sending the communication 11.05.2020
{{message_longdate}} full date of sending the message 11 May 2020.
{{message_month}} month of sending the message may
{{message_monthnumber}} message sending month number 05
{{message_year}} year of sending the message 2020

Information about the communication

Tag Description Example
{{message_id}} Message ID 11
{{message_guid}} unique GUID of the message being sent 6F9619FF-8B86-D011-B42D-00CF4FC964FF
{{message_subject}} subject New promotion only until the end of the week!

Sender information

Tag Description Example
{{sender_fromemail}} sender email [email protected]
{{sender_fromname}} sender name Some Brand
{{sender_replytoemail}} reply email [email protected]
{{sender_replytoname}} reply name Vasily Turkin

Using subscriber data fields

All dynamic content functions wrapped in {% %} are recommended to be wrapped in comments as well. <!-- -->We recommend wrapping all dynamic content functions wrapped in {% %} in comments, because comparison characters and other characters in DK conflict with HTML tags. The text or value to be output as a result should be outside the comments.

Substitution of a data field value

{{extrafield.name}}

Check the existence of a subscriber data field

{{isextrafieldexists_системное_имя_поля_данных}}

Comparing two data fields

<!--{% 
if (extraField.Name1 >= extraField.Name2) { %}--> 
  Some text
<!--{% }; %}-->

Changing the value of a data field when sending an email

{{setextrafield_name_value}}

Changing the value of a data field when clicking on a link in an email

<a href="{{SetExtraFieldByClick('https://link.com', 'EF_system_name', 'EF_value')}}">click</a>

Working with mailing groups

Unsubscribe a person from specific mailing groups

{{unsubscribe_groupname_groupname2}}

Unsubscribe from specific mailing groups with redirect to the specified URL

{{unsubscriberedirect_link_groupname_groupname2}}

Subscription of a person to specific mailing groups

{{subscribe_groupname_groupname2}}

Subscription to specific mailing groups with a redirect to the specified URL

{{subscriberedirect_link_groupname_groupname2}}

DOI confirmation link with redirect to the specified URL

{{ConfirmRedirect('http://mysite.com/')}}

Working with data types

Convert data field type to another data type

{% 
   var a = extraField.weight;
   var value = String(a);
   if (value === '60') { %}
     Вы весите 60 кг 
{% }; %}

Working with date and time

Returns the current time in unix timestamp format

{{timenow}}

Returns the transferred time in unix timestamp format

{{timeparse_2020-11-25_15:31}}

Adds the desired amount of time to the specified time. The first parameter is the time in unix timestamp format (can be obtained from TimeNow() or TimeParse()). The second parameter is the unit of time, possible values are 'sec', 'min', 'hour', 'day'. The third parameter is the amount of time (can be negative)

{{addtime_1603459057_min_3}}

Formats the received time in unix timestamp format to the passed format. The first parameter is the time, the second parameter is the format. The format is passed an example of how the date or time should be returned. The format works by constants, e.g. Mon Jan 2 15:04:05 MST 2006, 2020-01-02 18:24:05, etc.

{{timeformat_1603459057_2006-01-02_15:04:05}}

Text handling

Returns Base64 encoded string

{{base64encode_текст}}

Decodes the string

{{base64decode_0klqtdc60yhrggok}}

Parses XML to JSON

{{parsexml_xmlcontents}}

Working with external sources

Fetches data from any external source by specified link

{{HttpGet('https://link.com')}}

Snippets

A snippet is a snippet of code or text that is passed into transactional messages using API requests. Snippet values used in transactional messages can also be retrieved using dynamic content functions.

Substitute a snippet value

{{snippet_snippetname}}

Check if the snippet exists

{{issnippetexists_название_сниппета}}

Using a snippet in a conditional expression

{% 
   var value = Snippet('snippetName');
   if (value === '10') { 
%}
     Значение сниппета snippetName 10 
{% 
} else { 
     Abort()
   }
%}

Parsing XML from a snippet

Meaning of the snippet:

<Products>
  <Product>
    <product_id>12345</product_id>
  </Product>
</Products>
{% 
    var xmlSnippet = Snippet('xml');
    var xmlTpJson = ParseXML(xmlSnippet);
    //Вывод результата
    for(let key in xmlTpJson[0].Products.Product){
%}
    {{xmltpjson_0_.products.product_key_product_id}}
{% 
    }
%}

Snippet names should start with a small letter for correct display in the preview and substitution of values in the test letter.

<a href="{{DoNotTrackLink('https://link.com')}}">клик</a>

Stop sending a message

With JavaScript

{% 
   if ('Какое-либо условие') { %} 
     Какое-либо значение 
{% 
   } else { 
     Abort()
   }
%}

Using dynamic content

  {{abort}}

Work with trigger mechanics

Substitute N last or all products from the basket

{% 
var str = GetCart.Products;
    str.forEach(function(item, i, arr) { 
%} 
   {{item.productid}} 
{% 
   }); 
%}

Substitute N last or all products from favourites

{%
var str = GetFavourite.Products;
    str.forEach(function(item, i, arr) { 
%} 
  {{item.productid}} 
{% 
   }); 
%}

Return array of subscriber's opens

Accepts 3 or more parameters. The first parameter - maximum number of records to receive (maximum 100, if you pass zero, it will be 100). The second parameter - sort by date (possible values - DESC, ASC, Newest, Oldest). Third parameter - filter by date (should look like a string with operator and date in unix timestamp format. Possible operators >,>=,<,⇐,!=,=. Время можно получить методами работы со временем). Можно передавать несколько фильтров, например: GetOpens(10, Newest, '!= 1603459057', '!= 1603459058'), все фильтры работают через логическое и. Третий параметр может работать как период: возможные варианты - 'between 1603459057 and 1603459059', 'from 1603459057 to 1603459059'. 'from 1603459057 and 1603459059' тоже будет работать, нечувствителен к регистру, так же можно добавлять несколько таких параметров.

{{getopens_10_newest_1609888844}}

The GetOpens method returns an array of objects with fields:

  • count
  • productId
  • lastUpdate

Return array of subscriber's orders (similar to GetOpens)

{{getorders_100_desc_between_1603459057_and_1603459059}}

Return order information with all products and parameters by order ID

{{getorder_orderid}}

Working with data tables

To start using functions for data tables, you need to create an object/structure that will be the basis for the query:

{% var rows = Rows(); %}

To execute a query into a data table, all queries in DC must always end with an Execute() function

{% var rows = Rows().Execute(); %}

You can add a table using the

Table('TableName')

If this method is called more than once to one Row object, an error will occur.

The following methods are available for working with tables:

  • Get() - fetches one or more rows. The maximum limit and default value is 500.
  • GetAndDelete() - fetches one row and deletes it from the table.
  • Update() - updates a row or several rows, takes as an argument the column name and value to be changed. Multiple rows are possible.
  • Delete() - deletes rows by condition.
  • Insert() - adds a row or multiple rows.
  • Upsert() - add a row or several rows, if rows exist - update them.
  • IsExist() - returns boolean value of row existence by condition.

Auxiliary functions:

  • Limit(10) - limits the number of rows returned. It works only with the Get method, it won't do anything in other methods, but it won't break anything either
  • Offset(3) - Offset the search by the specified number of lines. Analogy to slq. Works only with the Get method, it will not do anything in other methods, but will not break anything either.
  • OrderBy('colName', DESC) - sorting. Sorting values are described below. Analogy of slq. It works only with Get method, it won't do anything in other methods, but it won't break anything either.
  • Where('colName', 'operator', 'val') - Conditions. Accepts parameters - column name, operator, values. The list of operators is below.

If there are multiple values, they will go through logical OR, example: Where('colName', 'operator', 'val', 'pal', 'cal'). If you make two conditions to the same Row object, they will go through logical AND, example: Where('colName', 'operator', 'val').Where('colName2', 'operator', 'pal'). Works with all functions except Insert and Upsert.

  • Set('colName', 'val') - sets the value of the column. It is possible to pass more than one pair. But if the number of incoming data is not even, the last element will be cut off to preserve the order (column name/value). Used with Insert, Upsert, Update methods
  • NewRow() is a command that allows you to save more than one row. To understand how it works, let's understand an example:

Rows().Insert().Table('someTable').Set('colName', 'val').Execute() - declare the add row method and tell it to add the value val to the colName column. Let's say we want to save another row, but have a different value in the colName column. Rows().Insert().Table('someTable').Set('colName', 'val').NewRow().Set('colName', 'val2').Execute() - so we will have two rows in the table.

Peculiarities of working with data tables:

  • All functions can be added in different order, but only Rows should be on the first place and Execute on the last place.
  • Where, Set, NewRow functions can be duplicated.
  • The Limit, Offset, OrderBy functions can be duplicated, but only the last value will be relevant.
  • In functions that modify data Insert, Update, Upsert, you can write column name/value pairs at once, bypassing the Set function: Rows().Insert('colName', 'val').Table('someTable')
  • To specify which columns to return using Get or GetAndDelete methods, you can pass column names to these functions: Get('col1', 'col2'…). If you don't pass anything, all columns will be returned. You can pass the * character, in this case all columns will be returned. Example: Get('*') - must be in quotes, otherwise the compiler will consider it as a multiplication sign.
  • The date must be passed in timestamp. You may use the TimeParse(), DateParse() functions for this purpose. For example, Where('date',inthisday,DateParse('2021-05-27'))))
  • When adding rows to tables, the Insert, Upsert, Set functions must contain the primary key, if there is one in the table (for example, Rows().Insert().Table('new_norm_table').Set('text', 'Independent media is independent because there is still something to eat in the provinces', 'num', 1000).Execute(), where num is the primary key).
  • Operators and sorts are written without inverted commas

Sorts

  • ASC - sorts from low to high values. OrderBy('num', ASC) or OrderBy('num', asc)
  • DESC - sorts from high values to low values. OrderBy('num', DESC) or desc - OrderBy('num', desc)
  • oldest - the lowest value. OrderBy('num', oldest)
  • newest - the highest value. OrderBy('num', newest)

Operators

  • equal, eq, EQ - equality. Where('num', equal, '111'), Where('num', eq, '111'), Where('num', EQ, '111'))
  • notequal, ne, NE - inequality. Where('num', notequal, '111')
  • beginwith - begins with. Where('email', beginwith, 'qwe')
  • endwith - ends with. Where('email', endwith, 'qwe')
  • contains - contains. Where('email', contains, 'qwe')
  • notcontains - does not contain. Where('email', notcontains, 'qwe')
  • morethan - more than. Where('num', morethan, '111')
  • moreorequalthan - greater than or equal to than. Where('num', moreorequalthan, '111')
  • lessthan - less than. Where('num', lessthan, '111')
  • lessorequalthan - less than or equal to than. Where('num', lessorequalthan, '111')
  • between - between. Where('num', between, '111', '11111')
  • isNull - equals zero. Where('num',isNull,'')
  • today - current day. Where('date',today,'') - no need to specify the value
  • inthisday - on a specific day. Where('date',inthisday,DateParse('2021-05-27') - condition on day equal to 27
  • inthisyear - current year. Where('date',inthisyear,'') - the value does not need to be specified
  • inthismonth - current month. Where('date',inthisday,'') - do not specify a value

Operators of arithmetic operations are written in quotes, they can also be used (Where('num', '=', '1')).

  • '='
  • '<ignore> <'
  • </ignore>''<='
  • '>'
  • '>='
  • '!='

Examples:

Rows().Get('*').Table('norm_table').Where('num', lessthan, '111').Execute();
Rows().Get('*').Table('norm_table').Limit(10).Where('num', '=', '1').Execute();
Rows().Get('*').Table('norm_table').Where('num', between, '111', '11111').Execute();
Rows().Get('*').Table('norm_table').Where('email', startwith, 'qwe').Execute();
Rows().Get('*').Table('norm_table').Where('email', notcontains, 'yopmail').Where('email', ne, '[email protected]').Execute();
Rows().Insert().Table('new_norm_table').Set('text', 'Независимые СМИ потому и независимы, что в провинциях ещё есть чем поживиться', 'num', 1000).Execute();
Rows().Get('*').Table('norm_table').Where('email', equal, '[email protected]', '[email protected]').Execute();
Rows().Delete().Table('new_norm_table').Where('num', '=', '2').Execute(); 

String/field output in an email

The result output is written in the following form:

{{название_переменной_номер_строки_.название_столбца}}

Example for the rows variable and the first row of the value column:

{{rows_0_.value}}

Working with SQL templates for dynamic content

You can use SQL-templates for dynamic content in emails (more information about their creation in this section ). this section).

To use the created template in an email, you need to access the template and write the information it returns to a variable. You can do this in the following way:

{% var name = GetByTemplate(123); %}

where:

  • name - variable name;
  • 123 - id of SQL-template.

For a template with a parameter, the code will look like this:

{% var name = GetByTemplate(123,{'param':value}); %}

Where:

  • name - variable name;
  • 123 - id of SQL-template;
  • param - name of the parameter in the SQL-template;
  • value - value to be substituted into the parameter.

The output of the value in the message will be standard :

{{name_0_.field}}

where:

  • name - variable name;
  • 0 - line number (index);
  • field - field name.

Working with goods

Method for getting an array of goods with parameters by identifiers. For the method to work it is necessary to configure import of product catalogue into enKod.

GetProducts('productid1', 'productid2')

where

  • productid1 and productid2 - identifiers of products in the catalogue

Example for getting products 3FF144 and 341FFDW with parameters

{%
var str = GetProducts('3FF144', '341FFDW');
    str.forEach(function(item, i, arr) { 
%} 
  Идентификатор товара {{dc:item.id}}
  Название товара {{dc:item.name}}
  Категория товара {{dc:item.category}}
  Любой другой параметр товара {{dc:item.param}}
{% 
   }); 
%}

Working with recommendation blocks

To receive and insert product recommendations into an email message, use the following method

GetRecoms('scriptId', 'productId')

where

  • scriptId - id of recommendation block in the service (mandatory)
  • productId - identifier of the product to which it is necessary to match recommendations for algorithms of similar or related products (optional)

To get the product parameters necessary for substitution into the letter, use the following construction

{{item.info.param}}

where

  • param - name of the required parameter from the commodity feed

To write values to the variable, as well as sequential output to the letter of the goods received by the method, use the following construct

{%
  var str = GetRecoms('scriptId', '');
  str.forEach(function(item, i, arr) { 
%}
Идентификатор товара {{dc:item.id}}
Название товара {{dc:item.info.name}}
Категория товара {{dc:item.info.category}}
Любой другой параметр товара {{dc:item.info.param}}
{%
  });
%}

where

  • scriptId - identifier of the recommendation block
  • {{item.id}}, {{item.info.name}} , {{item.info.category}} , {{item.info.param}} - product parameters to be inserted into the e-mail message

Please note that the number of received products is limited by the setting when creating a recommendation block.

Last modified: 2023.12.13 10:46 by Anastasia Aniskova