interpolate function

String interpolate(
  1. Locale locale,
  2. String string,
  3. Map<String, dynamic> variables,
  4. I18NextOptions options,
)

Replaces occurrences of matches in string for the named values in options (if they exist), by first passing through the I18NextOptions.formats before joining the resulting string.

  • 'Hello {{name}}' + {name: 'World'} -> 'Hello World'. This example illustrates a simple interpolation.
  • 'Now is {{date, dd/MM}}' + {date: DateTime.now()} -> 'Now is 23/09'. In this example, I18NextOptions.formats must be able to properly format the date.
  • 'A string with {{grouped.key}}' + {'grouped': {'key': "grouped keys}} -> 'A string with grouped keys'. In this example the variables are in the grouped formation (denoted by the I18NextOptions.keySeparator).

Implementation

String interpolate(
  Locale locale,
  String string,
  Map<String, dynamic> variables,
  I18NextOptions options,
) {
  final formatSeparator = options.formatSeparator ?? ',';
  final keySeparator = options.keySeparator ?? '.';
  final escapeValue = options.escapeValue ?? true;

  final todo = [
    _InterpolationHelper(
      interpolationUnescapePattern(options),
      (input) => input,
    ),
    _InterpolationHelper(
      interpolationPattern(options),
      escapeValue ? (options.escape ?? escape) : (input) => input,
    ),
  ];

  return todo.fold<String>(
    string,
    (result, helper) => result.splitMapJoin(helper.pattern, onMatch: (match) {
      var variable = match[1]!.trim();

      Iterable<String> formats = [];
      if (variable.contains(formatSeparator)) {
        final variableParts = variable.split(formatSeparator);
        variable = variableParts.first.trim();
        formats = variableParts.skip(1).map((e) => e.trim());
      }

      if (variable.isEmpty) {
        throw InterpolationException('Missing variable', match);
      }

      final path = variable.split(keySeparator);
      final value = evaluate(path, variables);
      final formatted = formatter.format(value, formats, locale, options) ??
          (throw InterpolationException(
              'Could not evaluate or format variable', match));
      return helper.escape(formatted);
    }),
  );
}