mirror of
https://github.com/home-assistant/core.git
synced 2025-05-10 17:09:17 +00:00
Avoid template context manager overhead when template is already compiled (#118079)
This commit is contained in:
parent
5cb3bc19c0
commit
6923fb1601
@ -511,11 +511,15 @@ class Template:
|
|||||||
|
|
||||||
def ensure_valid(self) -> None:
|
def ensure_valid(self) -> None:
|
||||||
"""Return if template is valid."""
|
"""Return if template is valid."""
|
||||||
with _template_context_manager as cm:
|
|
||||||
cm.set_template(self.template, "compiling")
|
|
||||||
if self.is_static or self._compiled_code is not None:
|
if self.is_static or self._compiled_code is not None:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if compiled := self._env.template_cache.get(self.template):
|
||||||
|
self._compiled_code = compiled
|
||||||
|
return
|
||||||
|
|
||||||
|
with _template_context_manager as cm:
|
||||||
|
cm.set_template(self.template, "compiling")
|
||||||
try:
|
try:
|
||||||
self._compiled_code = self._env.compile(self.template)
|
self._compiled_code = self._env.compile(self.template)
|
||||||
except jinja2.TemplateError as err:
|
except jinja2.TemplateError as err:
|
||||||
@ -2733,7 +2737,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
|
|||||||
super().__init__(undefined=make_logging_undefined(strict, log_fn))
|
super().__init__(undefined=make_logging_undefined(strict, log_fn))
|
||||||
self.hass = hass
|
self.hass = hass
|
||||||
self.template_cache: weakref.WeakValueDictionary[
|
self.template_cache: weakref.WeakValueDictionary[
|
||||||
str | jinja2.nodes.Template, CodeType | str | None
|
str | jinja2.nodes.Template, CodeType | None
|
||||||
] = weakref.WeakValueDictionary()
|
] = weakref.WeakValueDictionary()
|
||||||
self.add_extension("jinja2.ext.loopcontrols")
|
self.add_extension("jinja2.ext.loopcontrols")
|
||||||
self.filters["round"] = forgiving_round
|
self.filters["round"] = forgiving_round
|
||||||
@ -3082,10 +3086,9 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
|
|||||||
defer_init,
|
defer_init,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (cached := self.template_cache.get(source)) is None:
|
compiled = super().compile(source)
|
||||||
cached = self.template_cache[source] = super().compile(source)
|
self.template_cache[source] = compiled
|
||||||
|
return compiled
|
||||||
return cached
|
|
||||||
|
|
||||||
|
|
||||||
_NO_HASS_ENV = TemplateEnvironment(None)
|
_NO_HASS_ENV = TemplateEnvironment(None)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user