]>
git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/cephadm/template.py
2 from typing
import Optional
4 from jinja2
import Environment
, PackageLoader
, select_autoescape
, StrictUndefined
5 from jinja2
import exceptions
as j2_exceptions
8 class TemplateError(Exception):
12 class UndefinedError(TemplateError
):
16 class TemplateNotFoundError(TemplateError
):
21 def render(self
, name
: str, context
: Optional
[dict] = None) -> str:
22 raise NotImplementedError()
25 class Jinja2Engine(TemplateEngine
):
27 self
.env
= Environment(
28 loader
=PackageLoader('cephadm', 'templates'),
29 autoescape
=select_autoescape(['html', 'xml']),
32 undefined
=StrictUndefined
35 def render(self
, name
: str, context
: Optional
[dict] = None) -> str:
37 template
= self
.env
.get_template(name
)
39 return template
.render()
40 return template
.render(context
)
41 except j2_exceptions
.UndefinedError
as e
:
42 raise UndefinedError(e
.message
)
43 except j2_exceptions
.TemplateNotFound
as e
:
44 raise TemplateNotFoundError(e
.message
)
49 self
.engine
= Jinja2Engine()
51 'cephadm_managed': 'This file is generated by cephadm.'
54 def render(self
, name
: str, context
: Optional
[dict] = None, managed_context
=True) -> str:
55 """Render a string from a template with context.
57 :param name: template name. e.g. services/nfs/ganesha.conf.j2
59 :param context: a dictionary that contains values to be used in the template, defaults
61 :type context: Optional[dict], optional
62 :param managed_context: to inject default context like managed header or not, defaults
64 :type managed_context: bool, optional
65 :return: the templated string
70 ctx
= copy
.deepcopy(self
.base_context
)
71 if context
is not None:
72 ctx
= {**ctx
, **context
}
73 return self
.engine
.render(name
, ctx
)