declareVar
API Reference for the declareVar() string function
Overview
The declareVar function is the string equivalent of the <Var> component when working with declareStatic.
It marks dynamic content within declareStatic content that should be excluded from hash calculations and handled as variables at runtime.
function Component() {
function getGreeting(name) {
return "Hello, " + declareVar(name);
}
// Results in: "Hello, {_gt_, select, other {Brian}}"
gt(`${declareStatic(getGreeting(name))}. How are you?`);
// Results in: "Hello, Brian. How are you?"
return <p>{message}</p>;
}declareVar wraps dynamic content in an ICU-compatible placeholder that resolves to the original value at runtime.
If you want to remove the ICU markers, you can use decodeVars.
ICU Markers:
declareVar adds ICU-compatible markers to source text. Use decodeVars to extract the original value if needed for string processing.
Reference
Parameters
| Name | Type | Description |
|---|---|---|
value | value | string | number | boolean| undefined | null | The dynamic value to be marked as a variable. |
options? | Object | Options for the declareVar function. |
options.$name | string | The name of the variable, for translation context. (Similar to the name prop in the <Var> component) |
Returns
A string containing ICU-compatible markers that preserves the original value and is resolved at runtime.
Behavior
Variable Marking
When declareVar wraps a value, it:
- Converts the value to an ICU select statement format
- Marks it as dynamic content for translation processing
- Excludes it from translation hash calculations
- Preserves the original value for runtime interpolation
ICU Format
The function outputs ICU MessageFormat compatible strings:
declareVar("John") // → "{_gt_, select, other {John}}"Example
Basic Usage
Mark dynamic content within static functions.
import { declareStatic, declareVar, gt } from 'gt-next';
function getGreeting(name) {
return `Hello, ${declareVar(name)}!`;
}
function Component() {
const name = "Brian";
const message = gt(`${declareStatic(getGreeting(name))} Welcome back.`);
return <p>{message}</p>;
}With Other ICU Functions
You can use declareVar with other ICU functions to create more complex strings.
import { declareVar, declareStatic, useGT } from 'gt-next';
function Component({ name1, name2 }) {
const gt = useGT();
const message = gt("Hello, {name1}! My name is " + declareStatic(declareVar(name2)), { name1 });
return <p>{message}</p>;
// Results in: "Hello, Brian! My name is Archie"
}Notes
- Use
declareVaronly within functions called bydeclareStatic - The function adds ICU markers that may interfere with string processing
- Use
decodeVarsto extract original values when needed - Variables are excluded from translation and preserved at runtime
Next steps
- See
declareStaticfor creating static function calls in strings - See
decodeVarsfor extracting original values - See
<Var>for the JSX equivalent
How is this guide?