substitute static method

String substitute(
  1. String input,
  2. Map<String, String> variables, {
  3. bool allowUnresolved = false,
})

Substitutes all {{token}} occurrences in input using variables.

If allowUnresolved is false (default), throws UnresolvedTokenException if any token cannot be resolved from variables.

Implementation

static String substitute(
  String input,
  Map<String, String> variables, {
  bool allowUnresolved = false,
}) {
  final unresolved = <String>{};

  final result = input.replaceAllMapped(_tokenPattern, (match) {
    final key = match.group(1)!;
    if (variables.containsKey(key)) {
      return variables[key]!;
    }
    unresolved.add(key);
    return match.group(0)!;
  });

  if (!allowUnresolved && unresolved.isNotEmpty) {
    final sortedList = unresolved.toList()..sort();
    throw UnresolvedTokenException(sortedList);
  }

  return result;
}