Tuesday, November 8, 2011

Re: Template

2011/11/8 Hůla, Václav <ax@natur.cuni.cz>:
> Hello.
> How I do equivalent of foo[bar] in template? From documentation it
> looks like it should be done automatically - see
> https://docs.djangoproject.com/en/1.3/ref/templates/api/#render
>
> But:
>
>>>> from django.template import Context, Template
>>>> t = Template("Will ot work? {{ foo.bar }}")
>>>> context = {
> ...              'foo': {'baz':'Yes!'},
> ...              'bar': 'baz',
> ...              }
>>>>
>>>> c = Context(context)
>>>> t.render(c)
> u'Will ot work? '
>
>

You can't, at least not with Django's stock tags/filters. You can only
extract named keys:

foo["bar"] => {{ foo.bar }}

With a simple filter, you can add this functionality:

from django import template
register = template.Library()
@register.filter
def dict_get(hash, key):
"""
This little tag allows you to access a dictionary by key, when the key isn't
a simple string or integer. Very handy for accessing related maps.
"""
return hash[key]

and then:

{% load <name of tag library> %}
{{ foo|dict_get:bar }}

https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#writing-custom-template-filters

However, it is usually easier to simply ensure that your data is in a
useful format to be output by a template before passing it to the
template.

Cheers

Tom

--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate