Proper indentation in Django templates (without monkey-patching)?

旧街凉风 提交于 2019-11-29 11:07:16

Modifying the template layer would be ok, but not optimal, because it simply handles how a node is rendered, not an entire document. I would recommend writing custom middleware for your project to pretty-print the rendered response for html and css pages.

Your middleware will need to implement process_template_response which should be used to view and update the SimpleTemplateResponse object:

  • Check the is_rendered attribute to see if the response has been rendered
  • Verify the document type by either:
    • Looking for the desired file type (.html, .css) at the end of the template_name attribute
    • Looking at the content_type attribute (Django 1.5) or possibly mimetype for older installs
  • Re-format and update your rendered document to look gorgeous (Beautiful Soup is great for HTML, but you'll need to pick your preffered pretty-printer or roll your own).

I think Middleware is a far more elegant solution because this ultimately makes no lexical changes to your files. It is entirely separated from the logic that determines your template content (where it has no business being). Finally, you want ALL of your html and css to look great, so why tie that to your templates in the first place?

You could use class inheritance to create a different NodeList but it will probably require some patching on a different end. Your solution seems plain and simple.

class MyNodeList(NodeList):
    def render(self, context):
        # call super if you require so
        # your reindent functionality
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!