Liquid Type Casting (a.k.a Type Filters)

The blog post was written because sometimes, you may lose sanity trying to cast values/variables to the right types, while extending your Portal templates.

Liquid Type filters allow devs to cast values unto desired types for logic or information presentation purposes. There 4 type filters available:

  • boolean

  • decimal

  • integer

  • string

———————————————————————————————————————————————————

Boolean

Attempts to convert a value to boolean. If the value is already a boolean, the result will remain the same. Filter will also accept “on“, “enabled“, “yes“, “off“, “disabled“, or “no“.

Code
{{ true | boolean }}
{{ 'false' | boolean }}
{{ 'enabled' | boolean }}
Output
true
false
true
———————————————————————————————————————————————————

Decimal

Attempts to convert a value to decimal. If the value is already a decimal, the result will remain the same.

Code
{{ 10.1 | decimal }}
{{ '3.14' | decimal }}
Output
10.1
3.14
———————————————————————————————————————————————————

Integer

Attempts to convert a value to integer. If the value is already a integer, the result will remain the same.

Code
{{ 10 | integer }}
{{ '10' | integer }}
Output
10
10
———————————————————————————————————————————————————

String

Attempts to convert a value to string. If the value is already a integer, the result will remain the same.

Code
{{ 10 | string }}
Output
10

Other Considerations

All Type filters work in a similar fashion. In summary, if cast is invalid, the output will default to null. For example:

Code
{{ ‘I love Liquid‘ | boolean }}

Output
null

Victor Dantas