Ever since django.contrib.markup appeared I've added a markup_lang
field to my models where I want to support multiple input formats. This filter lets you pass the filter name as a string (from your model field, for example) and it will call the appropriate filter. I use None when the text is HTML, in which case it will return as-is.
Example:
class Article(models.Model):
content = models.TextField(null=False, default="")
markup_lang = models.CharField(maxlength=20, blank=True)
a = Article(content="**Test!**", markup_lang='textile')
b = Article(content="<h1>Hello!</h1>")
And in a template:
{% for article in article_list %}
{{ article.content|render_markup:article.markup_lang }}
{% endfor %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from django import template
register = template.Library()
@register.filter
def render_markup(string, markup_lang=None):
from django.contrib.markup.templatetags import markup
if markup_lang:
markup_lang = markup_lang.lower()
try:
return getattr(markup, markup_lang)(string)
except AttributeError:
raise ValueError("Markup filter %r not found." % markup_lang)
return string
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.