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

后端 未结 2 1846
耶瑟儿~
耶瑟儿~ 2020-12-19 16:49

I want to generate human-readable HTML and CSS code (properly indented) preprocessed by the Django template system for my standalone application.

I\'ve modified the

相关标签:
2条回答
  • 2020-12-19 17:02

    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
    
    0 讨论(0)
  • 2020-12-19 17:17

    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?

    0 讨论(0)
提交回复
热议问题