"""Parent template environment with single template per filename."""importosfromjinja2importEnvironment,FileSystemLoader,ChoiceLoaderfrom.pluginsimportlist_enabled,get_plugin_path
[docs]classFirstMatchLoader(ChoiceLoader):"""Custom loader that only returns the first matching template."""def__init__(self,loaders):super().__init__(loaders)self._template_cache={}
[docs]defget_source(self,environment,template):"""Get template source, returning only first match for each template name."""iftemplateinself._template_cache:returnself._template_cache[template]# Try each loader until we find the first matchforloaderinself.loaders:try:source=loader.get_source(environment,template)self._template_cache[template]=sourcereturnsourceexceptException:continue# If we get here, no loader could find the templateraiseTemplateNotFound(template)
[docs]defget_parent_templates_env(plugins=None):"""Set up Jinja2 environment that only loads first matching template. Args: plugins (list, optional): List of plugin names. Defaults to enabled plugins. Returns: Environment: Configured Jinja2 environment with FirstMatchLoader """ifpluginsisNone:plugins=list_enabled(False)template_paths=[]# Use list to maintain order# Add plugin template paths in priority orderforplugininplugins:plugin_path=get_plugin_path(plugin)ifnotplugin_path:continue# Add main template directorytemplate_dir=os.path.join(plugin_path,'templates')ifos.path.exists(template_dir):template_paths.append(template_dir)# Add parent directories to handle absolute paths# if it doesn't already exist in the listifos.path.dirname(plugin_path)notintemplate_paths:template_paths.append(os.path.dirname(plugin_path))ifos.path.dirname(os.path.dirname(plugin_path))notintemplate_paths:template_paths.append(os.path.dirname(os.path.dirname(plugin_path)))# Add default templates directory lasttemplate_paths.append('templates')print("**************************************************************************************")print("Loading templates from:",template_paths)# Create environment with FirstMatchLoaderloaders=[FileSystemLoader(path)forpathintemplate_paths]env=Environment(loader=FirstMatchLoader(loaders))returnenv