replace static method

String? replace(
  1. String? text,
  2. Map<String, Object>? variable
)

Implementation

static String? replace(String? text, Map<String, Object>? variable) {
  if (text == null) {
    return text;
  }
  if (variable == null) {
    return text;
  }
  if (!text.contains('{{') && !text.contains('}}')) {
    return text;
  }
  var regex = RegExp(r'[\\]?{{(?<varx>.*?)}}');
  var originText = text;
  while (true) {
    var match = regex.firstMatch(originText);
    if (match == null) {
      break;
    }
    var originDefined = match.group(0);
    if (originDefined == null) {
      print('Found variable but no group data');
      break;
    }
    var originVarx = originDefined.replaceAll('{{', '').replaceAll('}}', '');
    var varName = originVarx.trim();
    var varValue = variable[varName];

    if (originDefined.startsWith('\\')) {
      var tmpDefined = originDefined.replaceAll('\\{{', _tmpMark);
      originText =
          originText.replaceRange(match.start, match.end, tmpDefined);
      continue;
    }
    originText =
        originText.replaceRange(match.start, match.end, varValue.toString());
  }
  originText = originText.replaceAll(_tmpMark, '{{');
  return originText;
}