मैं अपने स्टैंडअलोन एप्लिकेशन के लिए Django टेम्पलेट सिस्टम द्वारा प्रीप्रोसेस्ड मानव-पठनीय एचटीएमएल और सीएसएस कोड (ठीक से इंडेंट) उत्पन्न करना चाहता हूं।Django टेम्पलेट्स में उचित इंडेंटेशन (बंदर-पैचिंग के बिना)?
मैंने django.template.base मॉड्यूल में मिले नोडलिस्ट क्लास से रेंडर विधि संशोधित की है। मेरा कोड ठीक से काम करता प्रतीत होता है, लेकिन मैं पुराने रेंडर विधि को बदलने के लिए बंदर-पैचिंग का उपयोग कर रहा हूं।
क्या कोई और शानदार तरीका है जो इस मामले में बंदर-पैचिंग का उपयोग नहीं करता है? या शायद बंदर-पैचिंग यहां सबसे अच्छा तरीका है?
मेरे कोड इस तरह दिखता है:
'''
This module monkey-patches Django template system to preserve
indentation when rendering templates.
'''
import re
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from django.template import Node, NodeList, TextNode
from django.template.loader_tags import (BlockNode, ConstantIncludeNode,
IncludeNode)
NEWLINES = re.compile(r'(\r\n|\r|\n)')
INDENT = re.compile(r'(?:\r\n|\r|\n)([\ \t]+)')
def get_indent(text, i=0):
'''
Depending on value of `i`, returns first or last indent
(or any other if `i` is something other than 0 or -1)
found in `text`. Indent is any sequence of tabs or spaces
preceded by a newline.
'''
try:
return INDENT.findall(text)[i]
except IndexError:
pass
def reindent(self, context):
bits = ''
for node in self:
if isinstance(node, Node):
bit = self.render_node(node, context)
else:
bit = node
text = force_text(bit)
# Remove one indentation level
if isinstance(node, BlockNode):
if INDENT.match(text):
indent = get_indent(text)
text = re.sub(r'(\r\n|\r|\n)' + indent, r'\1', text)
# Add one indentation level
if isinstance(node, (BlockNode, ConstantIncludeNode, IncludeNode)):
text = text.strip()
if '\r' in text or '\n' in text:
indent = get_indent(bits, -1)
if indent:
text = NEWLINES.sub(r'\1' + indent, text)
bits += text
return mark_safe(bits)
# Monkey-patching Django class
NodeList.render = reindent
मैं डीजेंगो के लिए बिल्कुल नया हूं, क्या आप एक उदाहरण प्रदान कर सकते हैं कि मैं इसे अपने प्रोजेक्ट में कैसे कार्यान्वित कर सकता हूं? –