- Author:
- MikiSoft
- Posted:
- July 4, 2016
- Language:
- Python
- Version:
- Not specified
- Score:
- 2 (after 2 ratings)
This is useful when you don't want to put any {% verbatim %}
tag in the file(s) you're including within template(s) (because you want it/them completely raw) and when you want to load such file(s) from static dir(s), as native {% include %}
tag can't achieve that (still).
Put the provided code in templatetags/rawinclude.py in your Django app, and then use it in your template(s) like this:<br>
{% load rawinclude %}{% raw_include 'file.html' %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage
register = template.Library()
@register.simple_tag
def raw_include(path):
if settings.DEBUG:
absolute_path = finders.find(path)
content = open(absolute_path).read()
else:
content = staticfiles_storage.open(path).read()
return mark_safe(content)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.