2010-11-15 103 views
0

我将视图中的变量i传递给模板。 当我打印{{subject.i.id}}时,它不起作用。 plz帮助尽快。 谢谢。模板中的django变量

# the view 
return render_to_response(
     'feedback/feedback.html', 
     {'subjects': subject_list, 'n': n, 'list': sub_list, 'i': 0}, 
     context_instance=RequestContext(request)) 

# the template 
{% for s in list %} 
    <div id="{{ subjects.i.id }}"> 
    {% for subject in s %} 
     <div> {{ subject }} </div> 
    {% endfor %} 
    </div> 
{% endfor %} 
+0

你的代码.. 。? – 2010-11-15 13:54:22

回答

3

你需要为这个模板过滤器工作

我的模板过滤器类似的情况:

import re 
from django import template 
from django.conf import settings 

numeric_test = re.compile("^\d+$") 
register = template.Library() 

def getattribute(value, arg): 
    """Gets an attribute of an object dynamically from a string name""" 
    if hasattr(value, str(arg)): 
      return getattr(value, arg) 
    elif hasattr(value, 'has_key') and value.has_key(arg): 
      return value[arg] 
    elif numeric_test.match(str(arg)) and len(value) > int(arg): 
      return value[int(arg)] 
    else: 
      return settings.TEMPLATE_STRING_IF_INVALID 

register.filter('getattribute', getattribute) 


# in the template 
{{ folder_info|getattribute:folder.id }} 
+0

回答得好,但是这是一个过滤器,而不是一个标签。 – 2010-11-15 14:35:24

0

是的,如果你附上代码,它会很好。确保你正确地呈现,和对象都有其兼容的属性名称

+0

#the view return render_to_response('feedback/feedback.html',{'subjects':subject_list,'n':n,'list':sub_list,'i':0},context_instance = RequestContext(request)) #模板 {list中%%对于s}

{% for subject in s%}
{{ subject }}
{%ENDFOR%}
{%ENDFOR%} – 2010-11-15 14:03:24