1

How to get the absolute file path of a template file from it's template name, without parsing the template?

E.g. given foo/bar.html return home/user/project/app/foo/templates/foo/bar.html

The django.template.loader.get_template will parse the template.

I think there was a django.template.loader.find_template but it was deprecated.

Please note this is not a duplicate of How to get the template path in the view django because that solution parses the whole template, which is slow when trying to find the path of many template_names.

Please note the templates files are spread across various apps in various places, so it needs to use the template loader engine to find them. hard coding some dir with suffixes won't work.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
run_the_race
  • 1,344
  • 2
  • 36
  • 62

1 Answers1

1

Reverse engineered this from the python source code:

import os
from django import template

def find_template(template_name: str) -> str:
    for engine in template.engines.all():
        for loader in engine.engine.template_loaders:
            for origin in loader.get_template_sources(template_name):
                if os.path.exists(origin.name):
                    return origin.name
    raise template.TemplateDoesNotExist(f"Could not find template: {template_name}")
run_the_race
  • 1,344
  • 2
  • 36
  • 62