parseTemplate
Parses a template string template
and replaces placeholders with actual values based on a parser
.
The parser
can be either a function or a non-function object. If the parser
is a function, it will be called with the matched pattern string as an argument and should return the actual value for replacement. If the parser
is a non-function object, getByPath will be used with the parser and the matched pattern string as arguments. The return value will replace the pattern.
If the actual value for replacement is undefined
or null
, the pattern string will be preserved.
Optional options
can be used to set the start and end delimiters of the pattern string.
Added in v0.0.2
Usage
ts
import { parseTemplate } from 'parsnip-kit'
const template0 = 'Hello, {name}! Your balance is {balance}.'
parseTemplate(template0, { name: 'Alice', balance: '$100' })
// 'Hello, Alice! Your balance is $100.'
parseTemplate(template0, (pattern: string) => data[pattern])
// 'Hello, Alice! Your balance is $100.'
const template1 = 'Are you called {info.name}?'
parseTemplate(template1, { info: { name: 'Administrator' } })
// 'Are you called Administrator?'
const template2 = 'Dear User [username], thank you for registering on our website.'
parseTemplate(template2, { username: 'John Titor' }, { start: '[', end: ']' })
// 'Dear User John Titor, thank you for registering on our website.'
API
Type Parameter
Arguments
Arg | Type | Optional | Default | Description |
---|---|---|---|---|
template | string | false | undefined | The template to replace |
parser | ObjectLike | ((pattern: string) => string | undefined | null) | false | undefined | To replace placeholders with actual value |
options | { start?: string, end?: string } | true | {} | To set the delimiters |
options.start | string | true | '{' | To set the start delimiters |
options.end | string | true | '}' | To set the end delimiters |
Returns
Type |
---|
string |