Login

render_markup filter, specify the markup filter as a string

Author:
exogen
Posted:
April 10, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.