template function

MessageTemplate template(
  1. String pattern
)

创建字符串模板辅助函数

支持 {placeholder} 语法进行变量插值。 如果上下文中不存在对应的键,保留原始占位符。

示例:

final tpl = template('服务器错误: {statusCode}');
final msg = tpl(error, {'statusCode': 500}); // "服务器错误: 500"

final tpl2 = template('{code}: {serverMessage}');
final msg2 = tpl2(error, {'code': 'E001', 'serverMessage': '用户不存在'});
// "E001: 用户不存在"

Implementation

MessageTemplate template(String pattern) {
  return (error, context) => pattern.replaceAllMapped(
        RegExp(r'\{(\w+)\}'),
        (match) {
          final key = match[1];
          final value = context[key];
          // 如果上下文中存在值则替换,否则保留原始占位符
          return value != null ? '$value' : match[0]!;
        },
      );
}