About In-memory Template Loader
When testing template functionality, you might want to use the locmem template loader with template content defined directly in the tests. Here's an example:
from django.template.loader import render_to_string
from django.test import SimpleTestCase, override_settings
# Use override_settings to inject a in-memory template loader
@override_settings(
TEMPLATES=[{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"OPTIONS": {
"loaders": [
# locmem loader: maps template names to strings in memory
(
"django.template.loaders.locmem.Loader",
{
"welcome.html": (
"{% load greeting_tags %}"
"<h1>{% greet full_name %}</h1>"
),
},
),
],
"builtins": [],
},
}]
)
class GreetTagTest(SimpleTestCase):
def test_greet_tag_renders(self):
result = render_to_string(
"welcome.html",
{"full_name": "World"}
)
self.assertEqual(result, "<h1>Hello, World!</h1>")
Tips and Tricks Programming Testing Templates Django 6.x Django 5.2 Django 4.2
Also by me
Django Messaging
For Django-based social platforms.
Django Paddle Subscriptions
For Django-based SaaS projects.
Django GDPR Cookie Consent
For Django websites that use cookies.