Django模板列表没有在for循环中打印

时间:2015-10-18 14:21:56

标签: python django

这是一个奇怪的问题,不确定这是一个错误还是我做过的傻事。

在我的views.py中,

def display(request):
    altTrue = []
    altFalse = []
    altTrue, altFalse = altCheck(soup)
    results = { 'alttrue' : altTrue,
                'altfalse' : altFalse,
              }
    return render(request, 'results.html', results)

def altCheck(soup):
    alttrue = []
    altfalse = []
    #The multimedia tags we're searching for
    multimedialist = ['img','input','area']
    #Return all tags from multimedia list and check if alt is present in them
    for tag in multimedialist:
        for incodetag in soup.findAll(tag):
            if incodetag.get('alt') is None:
                altfalse.append(incodetag)
            else:
                alttrue.append(incodetag)
    return alttrue, altfalse

在我的results.html中,

{{ alttrue }}   <!-- Prints out the list successfully -->
{% for tag in alttrue %}   <!--Prints out [] but with correct count-->
    {{ tag }}
{% endfor %}

我在尝试打印前确认列表是否为空,但仍然如此。通过for循环运行列表的那一刻,我得到的数量与列表中实际元素的数量一样多。[/ p>

奇怪的是,当我在我的Python解释器上尝试相同的事情时,我的结果很好,无论我是直接打印出对象还是使用了循环。

我错过了什么吗?

提前致谢!

1 个答案:

答案 0 :(得分:3)

问题出现是因为您的列表altTruealtFalse不是字符串列表,而是bs4.element.Tag的列表(即美丽的Soup元素标记)。

例如,如果您要将request功能更改为

def display(request):          
  content = '''
  <div>
      <img height="50" src="assets/images/logo.png" width="50"/>
  </div>
  '''
  soup = BeautifulSoup(content)
  altTrue = soup.findAll('img')
  results = {'alttrue': altTrue}
  return render(request, 'results.html', results)

然后:

{% for tag in alttrue %}
  {{ tag }}
{% endfor %}

...没有显示任何内容,因为您正在使用bs4.element.Tags列表。相反,您可以将display功能更改为

def display(request):          
    altTrue = ['one', 'two']
    results = {'alttrue': altTrue}
    return render(request, 'results.html', results)

然后HTML:

{% for tag in alttrue %}
  {{ tag }}
{% endfor %}

根据需要输出onetwo

因此,您需要将display功能更改为:

def display(request):
    altTrue = []
    altFalse = []
    altTrue, altFalse = altCheck(soup)
    altTrue = [item.name for item in altTrue]
    altFalse = [item.name for item in altFalse]    
    results = { 'alttrue' : altTrue,
                'altfalse' : altFalse,
              }
    return render(request, 'results.html', results)  
相关问题