Type Conversion
Template Engine will try to automatically convert the input data value to the expected data type.
Conversion Rules
For some data types, values can be automatically converted following the rules:
Numbers
If Number is expected, values of other data types can be converted as follows:
| Source | Number Representative |
|---|---|
Null Reference (null) | 0 |
| Undefined | 0 |
| Boolean | 1 for true, 0 for false |
| String | Will try to parse the number in the string |
| DateTime | Will convert to timestamp |
Boolean
If Boolean is expected, values of other data types can be converted as follows:
| Source | Boolean Representative |
|---|---|
Null Reference (null) | false |
| Undefined | false |
| String | false if empty, true otherwise |
| List or Map | false if empty, true otherwise |
| Number | false for 0, true otherwise |
String
If String is expected, values of other data types will be converted to string to the same form as it would print it using output code island.
DateTime
If DateTime is expected, values of other data types can be converted as follows:
| Source | DateTime Representative |
|---|---|
| String |
|
| Number | Will convert to date using this number as Unix timestamp |
Where it works?
Automatic data type conversion is available for:
- Operators and Expressions;
ifconstructs;- Functions arguments;
- Methods parameters with some exceptions and special behavior.
Data Type Conversion in Methods Parameters
Comparison Operations
Binary Comparison Operators (>, >=, <, <=, in, ==, !=) use the following algorithm:
- If both operands can be converted to a numbers, they are converted and compared as numbers;
- If at least one of the operands cannot be converted to a number, both operands are converted to strings and compared as strings.
This algorithm is universal, but in some cases the order of operations should be taken into account. For example:
{{ 'true' == 1 == true }}
{{ true == 1 == 'true' }}
It would seem that both expressions should print true, but the first one prints false.
First expression:
'true' == 1evaluates asfalse, because string'true'cannot be converted to a number, so both operands are converted to strings and compared as'true'and'1'that givesfalsein result;- Second operation becomes
false == truethat givesfalseas the final result of the whole expression.
Second expression:
true == 1evaluates astrue, because booleantruecan be converted to number1, so both operands are compared as numbers (they are equal);- Second operation becomes
true == 'true'that givestrueas the final result of the whole expression, but only because second operand'true'is string that cannot be converted to a number, so both operands are converted to strings and compared as'true'and'true'(they are equal).