vrde
vrde

Reputation: 937

Get the source of a Django template

I need to get the source of a template. I looked into the template APIs and into the source code with no success.

Apparently, the Template object keeps no reference to the original source.

Before messing up my codebase I'm asking: is there a simple way to get the source of a template?

Upvotes: 3

Views: 3937

Answers (4)

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)

Upvotes: 2

lanzz
lanzz

Reputation: 43168

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()

Upvotes: 5

Lucas
Lucas

Reputation: 597

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

Upvotes: 0

signal
signal

Reputation: 200

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".

Upvotes: -2

Related Questions