Templating for CLI output

I’m working on a personal project using Django to help me learn the framework better. I’ve implemented a bunch of custom commands so I can conveniently interact with my models and perform related tasks from the command line. I’ve developed a bunch of code that displays the contents of my models with an increasing amount effort going into layout and style. I’d like to refactor that code using a template-based approach, but after several hours of searching the web, I can’t find any commentary or prior art about this specific use case.

Here’s what I’ve cobbled together so far:

  • I know how to create templates and use django.template.loader.render_to_string to load and render them.
  • I know how to access django.utils.termcolors and use colorize() and make_style() to apply color to output. (not documented, found it in the source)
  • I know how to create and register a custom template filter that applies color to the input, and load and use it in my template.

I could proceed with a solution built on these pieces, but I wanted to ask experienced people:

  1. Am I do anything stupid, or is all of the above reasonable / optimal?
  2. Is there really no existing solution for this, like a template engine specifically for producing output for terminals, and addressing things like detecting terminal width and padding values with whitespace for complex layouts?

It occurs to me that I should probably share my code for the benefit of other novices that didn’t just spend hours figuring out what all those functions are.

  • myapp/templatetags/color.py
from django                         import template
from django.template.defaultfilters import stringfilter
from django.utils.termcolors        import colorize

register = template.Library()

def c(text, color):
    return colorize(text, fg=color)
  • myapp/templates/foo.term
{% load color %}{{ foo|c:"green" }}
  • anywhere (like django shell)
print(render_to_string( 'foo.term', dict(foo="success!") ))

Will print “success!” in green to your console.

There are a number of Python libraries available for managing console output. The curses library is part of the Python standard library, and so is always available. Additionally, there are third party libraries such as Rich adding additional features and make some operations a whole lot easier. I’d be looking at integrating one of those libraries in my code rather than trying to invent something. (I certainly wouldn’t recommend using any undocumented features. If something isn’t documented, then there’s no assurance that it will still be there in the next release or have the same functionality in a future release.)

1 Like

I didn’t know about Rich, but now that I do, I can add that to my search, which takes me to this neat thing: