inital commit
This commit is contained in:
28
server/app/mailer/domain/template.py
Normal file
28
server/app/mailer/domain/template.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
_FIELD_PATTERN = re.compile(r"(?<!\\)\$\{(.*?)(?<!\\)\}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class MailTemplate:
|
||||
template_string: str = ""
|
||||
|
||||
def set_template_string(self, template: str) -> "MailTemplate":
|
||||
self.template_string = template
|
||||
return self
|
||||
|
||||
def get_used_fields(self) -> set[str]:
|
||||
return set(_FIELD_PATTERN.findall(self.template_string))
|
||||
|
||||
def apply_values(self, values: dict[str, str], *, keep_missing: bool = True) -> str:
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
key = match.group(1)
|
||||
if key in values:
|
||||
return values[key]
|
||||
return match.group(0) if keep_missing else ""
|
||||
|
||||
rendered = _FIELD_PATTERN.sub(replace, self.template_string)
|
||||
return rendered.replace(r"\${", "${").replace(r"\}", "}")
|
||||
Reference in New Issue
Block a user