On Jun 15, 5:04 am, Greg Corradini <gregcorrad...@gmail.com> wrote: > Hello All, > > I'm try to get away from doing if/else in a template: > > {% if x.message|regtest == "True" %} > do something cool > {% else %} > do something less cool > {% endif %} > (snip)
> I would like to move to something like this in the template: > > {{ x.message|regtest }} > > given this template filter: > > def regtest(value): > regex = re.compile(r'^\*\*(?P<message>.*)\*\*') <ot> Explicitly calling re.compile in this case is at best useless. Either define your compiled regex object at the module level - so it's only compiled once at load time - or don't bother compiling it at all (the regex module keeps an internal cache of compiled expressions). </ot> > m = regex.match(value) > if m != None: return "<b><i>%s</i></b>"%value <ot> None is garanteed to be a singleton, so the identity test will be faster here (and is the canonical way to test against None FWIW) </ot> > else: return value <ot> Useless one-liners are considered bad style in Python. Using appropriate indentation helps wrt/ readability. if m != None: return "<b><i>%s</i></b>" % value else: return value </ot> > However, the html tags returned from the filter becomes part of the > element's text value instead of tags. So that's not working. https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping Hardcoding markup in a filter is not a great idea IMHO, but YMMV... -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.