On Fri, 2006-06-23 at 10:28 -0700, DavidA wrote:
> I'm trying to write a filter that will highlight substrings in text
> that matched a search pattern. I was hoping to do something like this:
> 
>    {{ obj.field|highlight:search }}
> 
> where 'search' is a template-context variable that is the string the
> user was searching for and the highlight filter would look something
> like:
> 
> @register.filter()
> def highlight(value, arg):
>     s = template.resolve_variable(arg, c)  # WHERE DO I GET THE CONTEXT
> FROM?
>     return re.sub('(%s)' % (s,),
>                   r'<span class="hightlight">\1</span>', value)
> 
> But I don't see a way to reference the template context ('c') in my
> filter, nor a way to pass the value of a variable from the template.

If the argument given to the filter is not enclosed in quotes, it is
treated as a variable that is looked up in the current context. So, in
your above example, the arg passed to highlight() will be the value of
"search". There is no need to resolve this yourself.

For more complex things that need access to other parts of the context,
use a template tag.

See, for example, the tests basic-syntax32 and timesince01 through
timeseince04 in tests/othertests/templates.py.

Regards,
Malcolm



--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to