Last active
October 28, 2019 14:23
-
-
Save stephan-nordnes-eriksen/4581b3fbb336bf9b3a1a5bbf796fcfbc to your computer and use it in GitHub Desktop.
Mini Templater implemented in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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