Bryan
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.
Adrian
--
Adrian Holovaty
holovaty.com | djangoproject.com | chicagocrime.org
I tried writing a rename template tag real quick, like so:
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]
@register.tag
def rename( parser, token ):
"""
{% rename from to %}
"""
tokens = token.contents.split()
if len( tokens ) != 3:
raise template.TemplateSyntaxError, \
"'%s' tag takes two arguments" % tokens[0]
return RenameNode( tokens[1], tokens[2] )
But I get this error I don't understand at all:
Exception Type: TypeError
Exception Value: sequence item 3: expected string, NoneType found
Exception Location:
/usr/lib/python2.4/site-packages/django/core/template/__init__.py in
render, line 703
A template tag to just display the list contents probably is more
straightforward, but if I can get that rename to work...
Bryan
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
That allows for variable creation, but of course you don't get the
django templates...
Cheers,
Tone