Login

render_markup filter, specify the markup filter as a string

Author:
exogen
Posted:
April 10, 2007
Language:
Python
Version:
.96
Tags:
filter markup
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. Analogue template filter to removetags that also removes the content of the tag by piquadrat 4 years, 8 months ago
  2. Form row filter by kylefox 7 years, 5 months ago
  3. filter for extracting a number of paragraphs from any HTML code by rafadev 4 years, 1 month ago
  4. i18n base model for translatable content by foxbunny 7 years, 1 month ago
  5. Filter on Multiple M2M Objects Simultaneously by axiak 8 years, 4 months ago

Comments

Please login first before commenting.