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()
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)
- [Django]-Django ModelForm – name 'Article' is not defined
- [Django]-Django: what do model and fields do in meta class?
- [Django]-How to adding middleware to Appengine's webapp framework?
- [Django]-Using a static website generator for a blog on a dynamic website?
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
- [Django]-Django REST Framework validation error: 'Enter a valid URL.'
- [Django]-Django project with a table prefix
-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”.