Variables
To use variables, declare them in a separate variables block in the card root. When declaring a variable, specify the following parameters:
name: Name, which can consist of uppercase and lowercase Latin characters, digits, and the characters_and.. It can't start with a digit or a dot.type: Type of variable. See Data types.value: Default value.
For example:
{
"variables": [
{
"name": "subscribed",
"type": "boolean",
"value": true
}
],
}
Data types
Supported data types:
- Boolean:
boolean - String:
string - Integer:
integer - Floating-point number:
number - Color:
color - Link to resource:
url(must be a valid URL) - Dictionary:
dict - Array:
array - Property:
property, see Properties
Examples of expression in variables initialization
{
"variables": [
{
"name": "subscribed",
"type": "boolean",
"value": true
},
{
"name": "likes",
"type": "integer",
"value": 0
},
{
"name": "black",
"type": "color",
"value": "#f000"
},
{
"name": "username",
"type": "string",
"value": "unknown"
}
],
"states": [ ... ]
}
Expressions in Variable Initialization
Variables support expressions in their initialization values. This allows you to reference other variables or use functions when defining a variable's initial value. The expression is evaluated once at the moment of variable initialization. The order of declaration matters - a variable can only reference variables that were declared before it.
{
"variables": [
{
"name": "margin",
"type": "integer",
"value": 8
},
{
"name": "padding",
"type": "integer",
"value": "@{margin * 2}"
},
{
"name": "total_spacing",
"type": "integer",
"value": "@{margin + padding}"
}
]
}
Warning
Avoid circular references between variables. If a variable references itself directly or indirectly through other variables, it will result in an initialization error.
Dictionaries
One of the available variable types is dictionaries. These are custom JSON objects that can store variables of any other type.
For instance, dictionaries are useful for declaring palettes and retrieving their values depending on the app theme:
"variables": [
{
"name": "palette",
"type": "dict",
"value": {
"light": {
"text_color": "#ffffff",
"text_background": "#0077FF"
},
"dark": {
"text_color": "#000000",
"text_background": "#0077FF"
},
"big": {
"text_size": 20
},
"small": {
"text_size": 16
}
}
},
{
"name": "app_theme",
"type": "string",
"value": "light"
},
{
"name": "font_size",
"type": "string",
"value": "small"
}
]
Dictionaries can't identify types automatically, so you need to use appropriate functions to retrieve their values:
getIntegerFromDict(dict_name, path_to_value)
getNumberFromDict(dict_name, path_to_value)
getStringFromDict(dict_name, path_to_value)
getColorFromDict(dict_name, path_to_value)
getUrlFromDict(dict_name, path_to_value)
getBooleanFromDict(dict_name, path_to_value)
getOptIntegerFromDict(fallback, dict_name, path_to_value)
getOptNumberFromDict(fallback, dict_name, path_to_value)
getOptStringFromDict(fallback, dict_name, path_to_value)
getOptColorFromDict(fallback, dict_name, path_to_value)
getOptUrlFromDict(fallback, dict_name, path_to_value)
getOptBooleanFromDict(fallback, dict_name, path_to_value)
With the dictionary declared in the example, you can use color and font size values as follows:
"background": [
{
"type": "solid",
"color": "@{getColorFromDict(palette, app_theme, 'text_background')}"
}
],
"font_size": "@{getIntegerFromDict(palette, font_size, 'text_size')}",
"text_color": "@{getColorFromDict(palette, app_theme, 'text_color')}"
View an interactive example
Arrays
Arrays contain arbitrary JSON objects.
"variables": [
{
"type": "array",
"name": "array",
"value": [
"string",
123,
"@{expression}"
]
}
]
Same as dictionaries, arrays can't identify the types of their elements automatically, so you need to use appropriate functions to retrieve their values:
getIntegerFromArray(array, index)
getNumberFromArray(array, index)
getStringFromArray(array, index)
getColorFromArray(array, index)
getUrlFromArray(array, index)
getBooleanFromArray(array, index)
getArrayFromArray(array, index)
getDictFromArray(array, index)
getOptIntegerFromArray(array, index, fallback)
getOptNumberFromArray(array, index, fallback)
getOptStringFromArray(array, index, fallback)
getOptColorFromArray(array, index, fallback)
getOptUrlFromArray(array, index, fallback)
getOptBooleanFromArray(array, index, fallback)
getOptArrayFromArray(array, index, fallback)
getOptDictFromArray(array, index, fallback)
len(array)
Using an incorrect function type or attempting to access an index outside the bounds of the array will result in an error. To avoid this, consider using the getOpt* function instead of get*. In this case, the fallback value will be returned instead of the error.
View an interactive example
Methods
For working with arrays and dictionaries, it's convenient to use methods. Unlike functions, methods are called directly from an array or dictionary and return the required value.
Available methods
|
Name |
Description |
Result type |
|
|
Returns a string representation of given value. |
|
|
|
Returns a string representation of given value. |
|
|
|
Returns a string representation of given value. |
|
|
|
Returns a string representation of given value. |
|
|
|
Returns a string representation of given value. |
|
|
|
Returns a string representation of given value. |
|
|
|
Returns a string representation of given value. |
|
|
|
Returns an array value from array by position. |
|
|
|
Returns a boolean value from array by position. |
|
|
|
Returns a color value from array by position. |
|
|
|
Returns a dict value from array by position. |
|
|
|
Returns an integer value from array by position. |
|
|
|
Returns a number value from array by position. |
|
|
|
Returns a string value from array by position. |
|
|
|
Returns a url value from array by position. |
|
|
|
The method returns boolean true if array is empty else false. |
|
|
|
Returns filtered array by calling boolean function to each element of array. Available platforms: web. |
|
|
|
Returns an array value from dict by key. |
|
|
|
Returns a boolean value from dict by key. |
|
|
|
Returns a color value from dict by key. |
|
|
|
Returns a dict value from dict by key. |
|
|
|
Returns an integer value from dict by key. |
|
|
|
Returns a number value from dict by key. |
|
|
|
Returns a string value from dict by key. |
|
|
|
Returns a url value from dict by key. |
|
|
|
Returns true if the given key is present in the dictionary. |
|
|
|
The method returns boolean true if dict is empty else false. |
|
|
|
Return a collection containing just the keys of the dictionary. |
|
|
|
Return a collection containing just the values of the dictionary. |
|
|
|
Returns a string value from an integer using format. |
|
|
|
Returns a string value from an number using format. |
|
|
|
Returns a string value from an integer using format and locale. |
|
|
|
Returns a string value from an number using format and locale. |
|
Complete descriptions of method fields and usage examples are available in the DivKit repository:
Field values
The method description includes the following fields:
-
function_name— method name. -
is_method— flag indicating whether the function is a method. For all methods, it has the valuetrue. -
doc— description of how the method works. -
arguments— list of arguments. Each argument is described by the values:-
type— type; -
doc— description; -
vararang— optional flag allowing this argument to accept not one, but multiple values of the required type.
-
-
result_type— type of the returned value.
View an interactive example
Properties
A variable of the property type does not store a value itself. When it is read, the expression from get is evaluated, and when its value is changed, the actions from set are performed.
value_type— return type of the property value. Required parameter.get— property value. Supports expressions. Required parameter.set— actions performed when the property value is set.new_value_variable_name— the name under which the new value is available in thesetactions. The default value isnew_value.
Example: a property that reads and changes a value in a dictionary
{
"variables": [
{
"name": "source",
"type": "dict",
"value": {
"color_key": "#AABBCC"
}
},
{
"name": "color_prop",
"type": "property",
"value_type": "color",
"get": "@{getColorFromDict(source, 'color_key')}",
"set": [
{
"log_id": "set_action_color",
"typed": {
"type": "dict_set_value",
"variable_name": "source",
"key": "color_key",
"value": {
"type": "string",
"value": "@{new_value}"
}
}
}
]
}
]
}
The color_prop property returns a color from the source dictionary. The set_variable action for color_prop writes the new value to that dictionary.
Changing the values of variables
To change the value of a variable, use the set_variable action. For example:
div-action://set_variable?name=common_text_size&value=17
To set the value for a variable, you can use calculated expressions and built-in functions.
Note
The type of a new value must match the variable type, otherwise the value can't be applied.
Note
You can use element-level local variables in URL actions. For example, to set a global variable based on a local variable value:
div-action://set_variable?name=result&value=@{local_value}
Examples:
-
Change the value of a floating-point variable:
div-action://set_variable?name=price&value=3.889 -
Change the value of a boolean variable:
true:div-action://set_variable?name=is_liked&value=1ordiv-action://set_variable?name=is_liked&value=truefalse:div-action://set_variable?name=is_liked&value=0ordiv-action://set_variable?name=is_liked&value=false
-
Change the
colortype variable to green:div-action://set_variable?name=color_variable&value=@{encodeUri('#ff00ff00')} -
Setting dictionary variables with expressions:
div-action://set_variable?name=result_dict&value=@{source_dict}Or using typed action format:
{ "type": "set_variable", "variable_name": "result_dict", "value": { "type": "dict", "value": "@{source_dict}" } }Note
The dictionary expression must evaluate to a valid dictionary value that matches the target variable type.
-
Setting dictionary variables from JSON objects:
Dictionary variables can be updated using typed actions with the dictionary value directly:
{ "log_id": "set_palette", "typed": { "type": "set_variable", "variable_name": "palette", "value": { "type": "dict", "value": { "light": { "text_color": "#e0bae3" } } } } }URL-encoded example
Dictionary variables can also be updated by providing a properly URL-encoded JSON string representation:
div-action://set_variable?name=palette&value=%7B%22light%22%3A%7B%22text_color%22%3A%22%23e0bae3%22%7D%7DThis corresponds to the following JSON structure:
{ "light": { "text_color": "#e0bae3" } }
Global variables
Variables that are declared within a layout are local and can't be accessed externally. To share variables between different layouts, use global variables.
To do this, declare a DivVariableController object on the client side and pass it the variables that need to be accessed from the layout.
Example for Android
Declare DivVariableController when creating DivConfiguration:
val variableController = DivVariableController()
val configuration = DivConfiguration.Builder(imageLoader)
.divVariableController(variableController)
.build()
Now you can pass a variable to the controller. For example, let's pass the string variable app_theme:
val theme = Variable.StringVariable("app_theme", "light")
variableController.putOrUpdate(theme)
Now all Div2View created using this DivConfiguration will have access to the app_theme variable. You can change a variable's value via the DivVariable#set method or DivVariableController#putOrUpdate. If this variable is already declared in the controller, its value will also be updated.
Example for iOS
Declare global variables storage and DivVariablesStorage in DivKitComponents:
let applicationStorage = DivVariableStorage()
let variablesStorage = DivVariablesStorage(outerStorage: applicationStorage)
let divkitComponents = DivKitComponents(variablesStorage: variablesStorage)
Now you can pass a variable to the global storage. For example, let's pass a dictionary with a palette:
let themeVariable: DivVariables = [
DivVariableName(rawValue: "palette"): .dict([
"text_color": "#ffffff",
"text_background": "#0077FF"
])
]
applicationStorage.put(themeVariable)
Now all DivView created using this DivKitComponent will have access to the palette variable.
DivKit uses two types of storages:
-
DivVariableStorage— base storage for variables. Use it for global application variables. It hasput()method to add variables and supports creating storage hierarchies throughouterStorage. -
DivVariablesStorage— manager for variables atDivKitComponentslevel. It manages card-level variables throughset(cardId:variables:)andappend(variables:for:)methods. Can haveouterStorageof typeDivVariableStoragefor accessing global variables.
Example for Web
Create GlobalVariablesController:
import {createVariable, createGlobalVariablesController} from '@divkitframework/divkit';
const controller = createGlobalVariablesController();
Now you can pass a variable to the controller. For example, let's pass a dictionary with a palette:
const palette = createVariable('palette', 'dict', {
"text_color": "#ffffff",
"text_background": "#0077FF"
});
controller.setVariable(palette);
Now all class instances created using this controller will have access to the palette variable.
Alert
Local variables are given precedence over global ones. If you declare a local variable that shares the same name as a global one, the global variable will be inaccessible. In addition, modifying a global variable from a layout changes it in DivVariableController, which means the variable will also change for all other layouts where it's used.
Element-level variables
Element-level variables are declared in the layout within the element they characterize.
Note
Variables can be declared for any element, not only for the card object.
View an interactive example
Variables for tracking element state
Some DivKit elements provide special variables for tracking their state. For example, the div-pager element allows tracking the number of visible elements through a variable:
Tracking the number of elements in a pager
The div-pager element supports the item_count_variable property, which allows you to specify the name of a variable for storing the number of visible elements in the pager.
Note
Elements with visible and invisible visibility status are included in the count. Elements with gone status are excluded. When using infinite scroll (infinite_scroll), virtual pages (duplicates) are not included in the actual number of elements.
{
"type": "pager",
"item_count_variable": "pager_item_count",
"items": [
{
"type": "text",
"text": "Page 1"
},
{
"type": "text",
"text": "Page 2"
}
]
}
The variable value is updated dynamically when:
- The number of elements in the pager changes
- The visibility of individual elements changes
- Elements are added or removed
This is useful for creating progress indicators, displaying the total number of pages, or conditionally showing UI elements:
{
"log_id": "pager_item_count_example",
"variables": [
{
"name": "pager_item_count",
"type": "integer",
"value": 0
}
],
"states": [
{
"state_id": 0,
"div": {
"type": "container",
"items": [
{
"type": "text",
"text": "Total pages: @{pager_item_count}"
},
{
"type": "pager",
"item_count_variable": "pager_item_count",
"items": [
{
"type": "text",
"text": "Page 1"
},
{
"type": "text",
"text": "Page 2"
},
{
"type": "text",
"text": "Page 3"
}
]
}
]
}
}
]
}
View an interactive example
Stored values
Values that are saved on the device and remain available after the app is restarted are described in Stored values.
Triggers
Running actions when variable values change is described in Triggers.
Learn more
You can discuss topics of interest in the DivKit user community in Telegram: https://t.me/divkit_community_en.