相关疑难解决方法(0)

Django 模板中的正确缩进(无需猴子修补)?

我想为我的独立应用程序生成由 Django 模板系统预处理的人类可读的 HTML 和 CSS 代码(正确缩进)。

我修改了 django.template.base 模块中 NodeList 类的 render 方法。我的代码似乎工作正常,但我使用猴子修补来替换旧的渲染方法。

在这种情况下,是否有一种更优雅的方式不使用猴子修补?或者也许猴子补丁是最好的方法?

我的代码如下所示:

'''
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 …
Run Code Online (Sandbox Code Playgroud)

django monkeypatching indentation django-templates

5
推荐指数
1
解决办法
2529
查看次数