Skip to content

Commit

Permalink
Cache the CMakeDeps Jinja2 templates (#13857)
Browse files Browse the repository at this point in the history
The compilation of the Jinja2 templates is quite slow, and several
templates needs to be compiled per dependency, so for larger projects
with a lot of dependencies it can be quite slow. This is fixed by
caching the templates per class instance.
  • Loading branch information
fredizzimo authored May 9, 2023
1 parent d01221b commit 9113454
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions conan/tools/cmake/cmakedeps/templates/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,15 @@ def render(self):
raise ConanException("error generating context for '{}': {}".format(self.conanfile, e))
if context is None:
return
return Template(self.template, trim_blocks=True, lstrip_blocks=True,
undefined=jinja2.StrictUndefined).render(context)

# Cache the template instance as a class attribute to greatly speed up the rendering
# NOTE: this assumes that self.template always returns the same string
template_instance = getattr(type(self), "template_instance", None)
if template_instance is None:
template_instance = Template(self.template, trim_blocks=True, lstrip_blocks=True,
undefined=jinja2.StrictUndefined)
setattr(type(self), "template_instance", template_instance)
return template_instance.render(context)

def context(self):
raise NotImplementedError()
Expand Down

0 comments on commit 9113454

Please sign in to comment.