api / const
tmpl
Tagged template function for string interpolation with signals.
Tagged template function for string interpolation with signals.
Creates a derived signal of the interpolated string that recomputes whenever any tracked expression changes.
Signature
export const tmpl = (
strings: TemplateStringsArray,
...tlExpressions: StringSignalDeriverTemplateExpressions
): DerivedSignal<string> =>
derive(() => {
return strings.reduce((acc, fragment, i) => {
let expValue;
const expression = tlExpressions[i];
if (typeof expression === "function") {
expValue = expression() ?? "";
} else if (valueIsSignalifiedObject(expression)) {
expValue = (expression as SignalifiedObject<any>).value ?? "";
} else {
expValue = (expression as any) ?? "";
}
return `${acc}${fragment}${expValue.toString()}`;
}, "");
});
Parameters
strings: The static string parts of the template literaltlExpressions: The dynamic expressions inside the placeholders
Returns
A derived signal of the interpolated string
Remarks
- Expressions can be signals, derived expression functions, or plain values
nullandundefinedbecome empty strings- Values are converted to strings via
.toString() - Works with any combination of supported expression types
Examples
const name = signal("World");
const greeting = tmpl`Hello ${name}`;
console.log(greeting.value); // "Hello World"
name.value = "Alice";
console.log(greeting.value); // "Hello Alice"
// Multiple expressions
const firstName = signal("John");
const lastName = signal("Doe");
const fullName = tmpl`${firstName} ${lastName}`;
// Mixed expressions
const count = signal(5);
const message = tmpl`Count: ${count}`;
// Function expressions
const doubled = tmpl`Double is ${() => count.value * 2}`;
See Also
- DerivedSignal - For the derived signal type
- derive - For the underlying derived signal primitive