format_string¶
The format_string filter enables you to format a string within your Experience Builder template using placeholders and optional arguments. It works similarly to the string interpolation ($"") or String.Format method in C#.
Functionality
- String Formatting: Takes a format string as the input. The format string can contain placeholders enclosed in curly braces
{}. - Arguments: Accepts a variable number of arguments that will be inserted into the placeholders in the format string. The arguments can be of any data type, including strings, numbers, dates, and even objects.
- Culture (Optional): Supports an optional named argument
cultureto specify the culture-specific formatting information. If not provided, the default culture will be used. - Output: Returns a new string with the formatted result.
Syntax
Arguments- arg1, arg2, ..., argn: The values to be inserted into the placeholders in the format string.
- culture (optional): A string specifying the culture to use for formatting (e.g., "en-US").
Code Samples
Example 1: Basic String Formatting
{% assign name = "Alice" %}
{% assign age = 30 %}
{{ "{0} is {1} years old." | format_string: name, age }}
Output:
Alice is 30 years old.
Example 2: Using Named Placeholders
{% assign product = { "name": "Widget", "price": 19.99 } %}
{{ "{product.name} costs {product.price:C}" | format_string }}
Output:
Example 3: Formatting with Culture Output:Outliers and Special Cases¶
- Mismatched Placeholders and Arguments: If the number of placeholders in the format string doesn't match the number of arguments provided, an error might occur.
- Invalid Format Specifiers: If the format string contains invalid format specifiers, an error might occur. Refer to the .NET format specifiers documentation for details.
- Null or Empty Arguments: If an argument is null or empty, it might be represented as an empty string or throw an error, depending on the specific format specifier used.
Key Points¶
- The
format_stringfilter provides a flexible way to dynamically construct strings with variables and custom formatting. - It allows you to use placeholders, formatting specifiers, and culture-specific formatting rules.
- Be mindful of the correct number of arguments and their types to ensure proper formatting and avoid errors.
- Leverage the
cultureargument to localize the output according to the user's preferences or region.