Login

Raw include from static dir tag

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

  1. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 weeks, 5 days ago
  2. codigo alto nivel by MrRocklion 2 months, 2 weeks ago
  3. Load template from specific app by Krzysiek555 3 months ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 1 week ago

Comments

Please login first before commenting.