Fillit
The fillit library allows you to create template files, read them into a class, and replace keys throughout the file by specifying key-value pairs to replace.
Installation
npm i -S @devtanc/fillit
yarn add @devtanc/fillit
Usage
folder contents
index.js
email.template.txt
email.template.txt
Hey there @recipientName,
This is @senderFirstName. Just shooting you a note to say @message.
@salutation,
@senderFirstName @senderLastName
index.js
const Template = require('@devtanc/fillit')
const path = require('path')
const emailTemplate = new Template({ path: path.resolve(__dirname, 'email.template.txt') })
emailTemplate.addPair('recipientName', 'Karl')
emailTemplate.addPair('senderFirstName', 'François')
emailTemplate.addPair('senderLastName', 'Lionet')
emailTemplate.addPair('message', 'I hope you\'re doing @howWell well')
emailTemplate.addPair('salutation', 'Hope to hear from you soon')
emailTemplate.addPair('howWell', 'fantastically')
emailTemplate.addPair(/shooting/, 'sending')
const result = emailTemplate.fill()
result
Hey there Karl,
This is François. Just sending you a note to say I hope you're doing fantastically well.
Hope to hear from you soon,
François Lionet
API
getPairs()
getResult()
getTemplate()
getKeyPattern()
addPair(key, value)
addPair([key, value])
addPairs(Map)
setKeyPattern(string)
fill()
fill(Map)
reset()
Important things to note
The result is modified and stored after each full <key, value>
replacement is complete. This makes is so that nested replacements are possible, as shown in the email example where @howWell
was found in a previous replacement, but not in the original template.
It is valid to set a RegExp as a key, which is also in the example. The RegExp is used in place of the key pattern for that round of <key,value>
replacement. The g
flag is set internally.