Skip to content

Function: templating() ​

templating(template, data, options?): string

Fill a template's placeholders with the values of an object or an array. {key} inserts the value as is, {{key}} inserts it HTML-escaped (&, ", ', <, >). A key is an index ({0}) or a path of properties separated by dots ({user.name}); its words may contain letters, digits, _, $ and -, and no spaces ({ name } is left as text). The values are converted with String(): null gives 'null', an object '[object Object]'; only undefined is missing.

Parameters ​

template ​

string

The template.

data ​

object | any[]

The values, by key: an object or an array.

options? ​

TemplatingOptions

What to do with the missing values, and a transformation of the values.

Returns ​

string

The filled template.

Throws ​

When template is not a string, or data is not an object (null passes this check, and its placeholders are then missing).

Throws ​

When a placeholder has no value and ignoreMissing is off.

Example ​

typescript
import {templating} from 'lakutata/utils'

console.log(templating('Hello {user.name}, you have {count} messages', {user: {name: 'Ada'}, count: 3}))
//Hello Ada, you have 3 messages
console.log(templating('<p>{{comment}}</p>', {comment: '<b>hi</b>'}))
//<p>&lt;b&gt;hi&lt;/b&gt;</p>
console.log(templating('{0} and {1}, {missing}', ['tea', 'cake'], {ignoreMissing: true}))
//tea and cake, {missing}

Released under the MIT License.