Using a string as template in CBV

Hi there! Is there a way in a CBV to swap out a real template with a string? So far I tried this and this, without luck.

Thanks in advance!

One probably inelegant way would be to use the locmem template loader: https://docs.djangoproject.com/en/3.1/ref/templates/api/#django.template.loaders.locmem.Loader

But your approach of overloading render_to_response seems like the right direction, perhaps it’s just missing the right invocation of TemplateResponse, or you need a TemplateResponse subclass.

1 Like

A sort of from-memory-loader is what I thought of too. Will give it a shot. Thanks!

Hey @valentinogagliardi — as I said on Twitter, you’re nearly there, but you’re probably importing the wrong class.

Compare django.template.backends.django.Template, which takes the request TemplateResponse is trying to pass to it with django.template.base.Template, which doesn’t.

You’re not really ever meant to use base.Template. (Why’s it there? History…) As per the Loading a template docs

The recommended way to create a Template is by calling the factory methods of the Engine : get_template() , select_template() and from_string() .

You want from_string():

>>> from django.template import engines
>>> django_engine = engines['django']
>>> template = django_engine.from_string("Hello {{ name }}!")
>>> template.render({"name":"Valentino"}, request=None)
'Hello Valentino!'

All those examples not using the backend API need to disappear, but likely never can.
HTH

Both solutions worked wonderfully! Thanks!