18 from pathlib
import Path
19 from os.path
import join
33 A dialog template renderer based on the mustache templating language. 41 Load a template by file name into the templates cache. 44 template_name (str): a unique identifier for a group of templates 45 filename (str): a fully qualified filename of a mustache template. 47 with open(filename,
'r', encoding='utf8') as f:
49 template_text = line.strip()
51 if (
not template_text.startswith(
'#')
and 60 template_text = re.sub(
r'\{\{+\s*(.*?)\s*\}\}+',
r'{\1}',
63 self.
templates[template_name].append(template_text)
65 def render(self, template_name, context=None, index=None):
67 Given a template name, pick a template and render it using the context. 68 If no matching template exists use template_name as template. 71 template_name (str): the name of a template group. 72 context (dict): dictionary representing values to be rendered 73 index (int): optional, the specific index in the collection of 77 str: the rendered string 79 context = context
or {}
85 return template_name.replace(
".",
" ")
87 template_functions = self.templates.get(template_name)
89 line = random.choice(template_functions)
91 line = template_functions[index % len(template_functions)]
93 line = line.format(**context)
100 Loads a collection of dialog files into a renderer implementation. 103 def __init__(self, renderer_factory=MustacheDialogRenderer):
108 Load all dialog files within the specified directory. 111 dialog_dir (str): directory that contains dialog files 114 a loaded instance of a dialog renderer 116 directory = Path(dialog_dir)
117 if not directory.exists()
or not directory.is_dir():
118 LOG.warning(
"No dialog files found: {}".format(dialog_dir))
121 for path, _, files
in os.walk(str(directory)):
123 if f.endswith(
".dialog"):
124 self.__renderer.load_template_file(
125 f.replace(
'.dialog',
''),
130 def get(phrase, lang=None, context=None):
132 Looks up a resource file for the given phrase. If no file 133 is found, the requested phrase is returned as the string. 134 This will use the default language for translations. 137 phrase (str): resource phrase to retrieve/translate 138 lang (str): the language to use 139 context (dict): values to be inserted into the string 142 str: a randomized and/or translated version of the phrase 147 lang = Configuration.get().
get(
"lang")
149 filename =
"text/" + lang.lower() +
"/" + phrase +
".dialog" 152 LOG.debug(
"Resource file not found: {}".format(filename))
156 stache.load_template_file(
"template", template)
159 return stache.render(
"template", context)
def resolve_resource_file(res_name)
def load_template_file(self, template_name, filename)
def load(self, dialog_dir)
def __init__(self, renderer_factory=MustacheDialogRenderer)
def render(self, template_name, context=None, index=None)
def get(phrase, lang=None, context=None)