On Sun, Oct 23, 2011 at 10:18 AM, Lee <[email protected]> wrote:
> New to template language. I've perused the docs but can't find how to
> do basic string operations like regex match/replace on {{ string
> variables }} within a template. Can someone please steer me to the
> right docs?
The reason you haven't found any docs on how to use regex
match/replace in Django's template language is because that sort of
thing isn't possible.
Django's template language isn't a general programming language. This
is a specific design constraint. We've gone to great lengths to make
it difficult to put business logic in a Django template, and if you're
talking about putting regular expressions in a template, it sounds
like that's what you're trying to do.
So -- what you really need to ask is "what am I trying to do with a
regular expression?" I'm going to guess that the use case is something
like cleaning up/modifying a label to meet some sort of display
requirement. If this is the case, then one way to address this would
be to use a template filter. A template filter is just a Python
function that can be used to transform a template variable into a
different form.
In a template tag module, you define something like:
@register.filter
def cleanup(value):
return re.sub(value, ...)
Then, in your template,
{% load mytagmodule %}
{{ myvariable|cleanup }}
This keeps the business logic -- how to "cleanup" the text -- separate
from the template itself. It also means that the regex code is
reusable -- you won't have to reproduce the regex every time you need
to do that particular substitution.
If you have more complex requirements, you may need to look into a
custom template tag.
For more details, see the docs on custom template filters and tags:
https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/
Yours,
Russ Magee %-)
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.