Skip to content

Instantly share code, notes, and snippets.

@stephan-nordnes-eriksen
Last active October 28, 2019 14:23
Show Gist options
  • Save stephan-nordnes-eriksen/4581b3fbb336bf9b3a1a5bbf796fcfbc to your computer and use it in GitHub Desktop.
Save stephan-nordnes-eriksen/4581b3fbb336bf9b3a1a5bbf796fcfbc to your computer and use it in GitHub Desktop.
Mini Templater implemented in typescript
/**
* Parse Configuration for the MiniTemlater. This is essentially just a JavaScript object
*/
export interface ParseConfig {
[key: string]: string
}
/**
* MiniTemplater is a super-simple templating engine.
*
* Example:
* import {MiniTemlater} from 'miniTemplater'
* let templateText = "Some text including {{thisTag}}"
* let templateConfig = {thisTag: 'My Data'}
* let renderedText = MiniTemlater(templateText, templateConfig)
* console.log(renderedText)
* // => "Some text including My Data"
*
* @param templateText Input text potentially containing the handlebars-style tags (eg. {{myTag}})
* @param config Parse configuration containing the translate information (eg. {myTag: "My custom data})
*/
export function MiniTemplater(templateText: string, config: ParseConfig) {
return templateText.replace(/\{\{\S+\}\}/g, (match) => {
const matchExtract = match.substring(2, match.length - 2)
const configMatch = config[matchExtract]
if (configMatch) {
return configMatch
} else {
return match
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment