Skip to content

Instantly share code, notes, and snippets.

@goinnn
Created January 18, 2019 13:35
Show Gist options
  • Save goinnn/8a42314fccdd13bcf4df256a277ec1f6 to your computer and use it in GitHub Desktop.
Save goinnn/8a42314fccdd13bcf4df256a277ec1f6 to your computer and use it in GitHub Desktop.
import re
from django.core.management.base import BaseCommand
from django.template import base, defaulttags
from django.template.loader import get_template
from django.template.base import TextNode
# Monkey patching
render_tags = ('block ', 'endblock ', 'extends ', 'include ')
BLOCK_TAG_START = []
BLOCK_TAG_START2 = '%s (%s)' % (re.escape('{%'), '|'.join(render_tags))
for tag in render_tags:
BLOCK_TAG_START.append('{%% %s' % tag)
base.BLOCK_TAG_START = tuple(BLOCK_TAG_START)
base.VARIABLE_TAG_START = '{{ block.super'
base.tag_re = (re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)' %
(BLOCK_TAG_START2, re.escape(base.BLOCK_TAG_END),
re.escape(base.VARIABLE_TAG_START), re.escape(base.VARIABLE_TAG_END),
re.escape(base.COMMENT_TAG_START), re.escape(base.COMMENT_TAG_END))))
# End monkey patching
from django.template.base import VariableNode
def do_load(parser, token):
defaulttags.register.tags['load_original'](parser, token)
return TextNode('{%% %s %%}' % token.contents)
defaulttags.register.tags['load_original'] = defaulttags.register.tags['load']
defaulttags.register.tags['load'] = do_load
def render_patch(self, context):
if self.filter_expression.token == 'block.super':
return self.render_original(context)
return "{{ %s }}" % self.filter_expression.token
VariableNode.render_original = VariableNode.render
VariableNode.render = render_patch
class Command(BaseCommand):
args = '<None>'
help = 'Update employees'
def handle(self, *args, **options):
unify_templates = ['admin/index.html']
for unify_template in unify_templates:
template = get_template(unify_template)
template_unify = template.render({})
destination_name = template.origin.name.replace('.html', '.unify.html')
print(destination_name)
f = open(destination_name, 'w')
f.write(template_unify)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment