feat: rich text template (#68)
* feat: add file * feat: add template convert function * refactor: update function
This commit is contained in:
parent
14f3c17be4
commit
6efce3c4bb
1 changed files with 34 additions and 0 deletions
34
src/utils/string-template.ts
Normal file
34
src/utils/string-template.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
const templates = {
|
||||||
|
'my-template': {
|
||||||
|
converter: (context?: number[]) => {
|
||||||
|
return context?.join(', ') || '';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
type Template = typeof templates;
|
||||||
|
type TemplateName = keyof Template;
|
||||||
|
type TemplateContext = {
|
||||||
|
[key in TemplateName]: Parameters<Template[TemplateName]['converter']>[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function convertTemplate(
|
||||||
|
text: string,
|
||||||
|
context?: TemplateContext,
|
||||||
|
templateUse?: TemplateName[],
|
||||||
|
) {
|
||||||
|
let ret = text;
|
||||||
|
|
||||||
|
for (const [name, template] of Object.entries(templates)) {
|
||||||
|
if (templateUse && !templateUse.includes(name as TemplateName)) continue;
|
||||||
|
|
||||||
|
ret = text.replace(
|
||||||
|
new RegExp('\\#\\[' + name.replaceAll('-', '\\-') + '\\]', 'g'),
|
||||||
|
typeof template.converter === 'function'
|
||||||
|
? template.converter(context?.[name as TemplateName])
|
||||||
|
: template.converter,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue