About Dedenting Markdown Text
If you have a multiline docstring or any other string containing Markdown that needs to be parsed later, it's a good idea to use the dedent()
function. This ensures the content is not mistakenly interpreted as a blockquote:
class Example:
"""
# Example Class
This class demonstrates how to:
- Dedent multiline help text
- Convert it from Markdown to HTML
- Return the formatted output
"""
@classmethod
def get_help_html(cls):
"""Returns the class docstring as HTML."""
from textwrap import dedent
from markdown import markdown
if doc := cls.__doc__:
doc = dedent(doc).strip()
return markdown(doc)
return ""
Now if we print the help text, we'll get this:
>>> obj = Example()
>>> print(obj.get_help_html())
<h1>Example Class</h1>
<p>This class demonstrates how to:</p>
<ul>
<li>Dedent multiline help text</li>
<li>Convert it from Markdown to HTML</li>
<li>Return the formatted output</li>
</ul>
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django App for You
Django GDPR Cookie Consent app
For Django websites that use cookies.
Django App for You