From 8025bb84a85373dd36d99d78978a7d6e5c1dd5fa Mon Sep 17 00:00:00 2001 From: Piotr Machowski <6118709+PiotrMachowski@users.noreply.github.com> Date: Fri, 20 Sep 2024 04:30:15 +0200 Subject: [PATCH] Add passing context to evaluation of ct_eval --- custom_components/custom_templates/__init__.py | 3 ++- .../custom_templates/templates/eval_template.py | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/custom_components/custom_templates/__init__.py b/custom_components/custom_templates/__init__.py index b5e2a16..110b690 100644 --- a/custom_components/custom_templates/__init__.py +++ b/custom_components/custom_templates/__init__.py @@ -1,5 +1,6 @@ import logging from typing import Any, Callable +from jinja2 import pass_context from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.core import Event, HomeAssistant @@ -51,7 +52,7 @@ async def _async_load_translations(_: Event) -> None: state_attr_translated_template = StateAttrTranslated(hass, languages) translated_template = Translated(hass, languages) all_translations_template = AllTranslations(hass, languages) - eval_template = EvalTemplate(hass) + eval_template = pass_context(EvalTemplate(hass)) is_available_template = IsAvailable(hass) dict_merge_template = DictMerge(hass) diff --git a/custom_components/custom_templates/templates/eval_template.py b/custom_components/custom_templates/templates/eval_template.py index 1e6cdec..85615e5 100644 --- a/custom_components/custom_templates/templates/eval_template.py +++ b/custom_components/custom_templates/templates/eval_template.py @@ -9,9 +9,14 @@ class EvalTemplate: def __init__(self, hass: HomeAssistant) -> None: self._hass = hass - def __call__(self, content: str) -> Any: + def __call__(self, passed_context: dict, content: str, variables: dict | None = None, parse_result: bool = True, pass_context: bool = True) -> Any: + context = {} + if pass_context: + context = context | pass_context + if variables is not None: + context = context | variables tpl = Template(content, self._hass) - return tpl.async_render() + return tpl.async_render(variables=context, parse_result=parse_result) def __repr__(self) -> str: return "