On 1/18/06, Bryan Murdock <[EMAIL PROTECTED]> wrote:
> On 1/18/06, Adrian Holovaty <[EMAIL PROTECTED]> wrote:
> >
> > On 1/17/06, Bryan Murdock <[EMAIL PROTECTED]> wrote:
> > > Is it possible to somehow rename or assign one variable to another in
> > > a template?  All the generic views provide an object_list, except
> > > archive_index which provides latest.  I'm trying to write a generic
> > > template that loops through the object_list (or latest) for all the
> > > date-based generic views, but that name difference makes it tough.
> >
> > No, the template system doesn't support renaming or assigning
> > variables, and there are no plans to add that functionality. In your
> > case, if you're concerned about repeating template code, I'd suggest
> > writing a template tag that does the work of displaying output for the
> > object_list/latest.
>
> I tried writing a rename template tag real quick, like so:

In case anyone was left hanging here, I got rename to work:

>
> from django.core import template
>
> register = template.Library()
>
> class RenameNode( template.Node ):
>     def __init__( self, fromvar, tovar ):
>         self.fromvar = fromvar; self.tovar = tovar
>
>     def render( self, context ):
>         context[self.tovar] = context[self.fromvar]

render needed to return ''.  Also, in order to do something like:

{% rename object.get_relatedObject_list relatedObject_list %}

I found this nice resolve_variable function.  The final rename.py is this:

from django.core import template
from django.core.template import resolve_variable

register = template.Library()

class RenameNode( template.Node ):
    def __init__( self, fromvar, tovar ):
        self.fromvar = fromvar; self.tovar = tovar

    def render( self, context ):
        context[self.tovar] = resolve_variable( self.fromvar, context )
        # very important: don't forget to return a string!!
        return ''

@register.tag
def rename( parser, token ):
    tokens = token.contents.split()
    if len( tokens ) != 3:
        raise template.TemplateSyntaxError, \
              "'%s' tag takes two arguments" % tokens[0]
    return RenameNode( tokens[1], tokens[2] )

It came in pretty handy for me.

Bryan

Reply via email to