[Django]-Get the source of a Django template

5👍

The Template objects don’t keep a reference to the original source, but they do keep a reference to the original source file and you can re-read the source from there:

source = open(template_instance.origin.name, 'r').read()
👤lanzz

2👍

If you know exactly what loader is loading template you can use Loader method directly.

from django.template.loaders.app_directories import Loader
source = Loader.load_template_source(file_name)[0]

file_name is same as when loading templates with loader.get_template(file_name)

0👍

There is a great shortcut called render_to_string.

As de docs says:

It loads a template, renders it and returns the resulting string:

from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})

So, the variable rendered is a string with the source code of the template

👤Lucas

-2👍

Templates are text files (usually, HTML, but not necessarily) that get rendered with a context (usually) when called from a call to, for instance, django.shortcuts.render. If you have a view function, that should specify which template it’s using.

From the docs:

from django.shortcuts import render

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {"foo": "bar"},
        content_type="application/xhtml+xml")

Here, the template would be “templates/myapp/index.html”.

👤signal

Leave a comment