Login

Pretty Print Template Tag

Author:
paulvrutledge
Posted:
May 22, 2014
Language:
Python
Version:
1.6
Tags:
beautiful-soup template-tag pretty-print
Score:
1 (after 1 ratings)

This defines a new template tag that lets you print your rendered templates (or partial templates) in html that has been prettified by beautiful soup. It is dependent on the beautiful soup library (bs4). Not recommended for production but it is helpful for development and serving readable html.

{% load whatever_template_file %}'

   <body>

     {% pretty %}
         <h1>Hello, world.</h1>
     {% endpretty %}

   </body>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.template import Node

class PrettyPrintNode(Node):
 
    def __init__(self, nodelist):
        self.nodelist = nodelist
 
    def render(self, context):
        from bs4 import BeautifulSoup
        html = BeautifulSoup(self.nodelist.render(context))
        return html.prettify()
 
 
@register.tag()
def pretty(parser,token):
 
    nodelist = parser.parse(('endpretty',))
    parser.delete_first_token()
    return PrettyPrintNode(nodelist)

More like this

  1. Analogue template filter to removetags that also removes the content of the tag by piquadrat 4 years, 3 months ago
  2. YUI Loader as Django middleware by akaihola 6 years, 10 months ago
  3. Output sql_queries in Firebug console when in debug mode by wojas 4 years, 11 months ago
  4. A dict template tag by Batiste 6 years, 10 months ago
  5. whitespaceoptimize block tag by peterbe 6 years, 5 months ago

Comments

Please login first before commenting.