inject function
Injects data into a string template using slot placeholders.
This function replaces slot placeholders in a string with actual data values.
Slots are defined using XML-like tags: <slot>key</slot>
.
The function supports:
- Multiple slot replacements in a single string
- Map-based data injection (using keys as slot names)
- Error handling for missing or invalid data
- Fallback to original string if injection fails
Parameters:
name
: The slot name to look for (e.g., "slot", "param")data
: Data map containing values to injectinput
: String template containing slot placeholders
Returns:
- String with slots replaced by actual data values
Example:
final result = inject(
"slot",
{"title": "Product Name", "price": "29.99"},
"Product: <slot>title</slot> - $<slot>price</slot>"
);
// Result: "Product: Product Name - $29.99"
Implementation
String inject(String name, Object data, Object input) {
String result = input.toString();
try {
/// Find all placeholders enclosed in <slot> tags
RegExp slotRegExp = RegExp("<$name>(.*?)</$name>");
Iterable<Match> matches = slotRegExp.allMatches(input.toString());
if (data is Map) {
/// Iterate over matches and replace with values from data map
for (Match match in matches) {
String slotName = match.group(1)!;
/// Extract the slot name
String slotValue = data[slotName].toString();
/// Use value from data map
result = result.replaceFirst(match.group(0)!, slotValue);
}
/// Return original input if result is empty
if (result.trim() == "") {
return input.toString();
}
}
} catch (e) {
/// Log injection errors for debugging
printLog("Injection Error: $e", true, color: LogColor.red);
}
return result;
}