Dojo String Substitute
February 26th 2013
I recently developed some code that required the use of dojo.string.substitute. I have used this module before but I never really researched it’s full potential. I understand it is the basis for Dojo’s Dijit templating. I needed to know more…
Overview
The function performs parameterized substitutions on a string template.
Method Signature
string.substitute(template, map, transform, scope)
| template | String | a string with expressions in the form ${key} to be replaced or ${key:format} which specifies a format function. keys are case-sensitive. |
|---|---|---|
| map | Object|Array | hash to search for substitutions |
| transform | Function | a function to process all parameters before substitution takes place |
| scope | Object | where to look for optional format function; default to the global namespace |
Usage
The string template is written as a regular string with ${} expression in the place where a substitution is required. ${} expression references a position in an Array or a member of an Object structure.
The method can be used a number of ways.
with Array
- substitutes expressions in a string with values from an Array.
with Object
- substitutes expressions in a string with values from a JSON Object.
Object and Transformer
- substitutes expressions in a string with values from a JSON Object, but uses a transformer to modify the text before rendering.
Object and Formatter
- substitutes expressions in a string with values from a JSON Object, but uses the dojo.string module as a formatter.