2015-11-03 81 views
3

一個特定的字典項我有一個靜態dictionary的Python瓶:訪問模板

urls = { 
    'foo': 'http://example.com', 
    'bar': 'http://example2.com', 
    'test': 'http://example3.com'} 

然後,我有一個元組列表。每個tuple包含以前字典的一個關鍵:

myList = [('bar', 0.9),('test', 0.7),('foo', 0.5)] 

我希望把我的模板中的相關網址爲按降序每個密鑰字符串,因爲它們在列表中(與reverse = True集創建in this way明顯) 。

在我已經試過這一點,但是,如預期的模板,這是行不通的:

{% for i in myList %} 
<tr> 
<a href= " {{ urls[i[0]] }} "> 
    <td> 
    {{ i[0] }} 
    </td> 
</a> 
</tr> 
{% endfor %} 

所以,我怎麼能訪問dictionary元素?

+2

你得到了什麼錯誤的,什麼是你的'render_template'代碼看起來像? – Doobeh

+0

沒有錯誤,只是超鏈接不工作,我只是文本 – accand

+1

我看不到你的字典格式正確。我已經初始化它,像這樣:'url = {0 {0 {0}'''''':'http://example.com', 'bar':'http://example2.com', 'test':'http: //example.com', }' – ferdy

回答

1

您生成的HTML錯誤。

不要將表格元素放入鏈接文本中。

我測試過的純HTML這樣的:

<table> 
    <tr> 
    <a href= " http://google.de "> 
     <td> Fooo 
     </td> 
    </a> 
    </tr> 
</table> 

,它會導致「死」的鏈接。把全a href到您的<td>代替:

<table> 
    <tr> 
    <td> 
     <a href= " http://google.de "> 
     Fooo 
     </a> 
    </td> 
    </tr> 
</table> 
+2

關於「你說的代碼不起作用嗎?它不起作用」。 –

+0

這不是問題,它適用於靜態URL – accand

+0

嗨,我的錯誤,你的解決方案是正確的。但我並沒有讓你失望,事實上我沒有足夠的聲望。對號碼爲 – accand

0

您需要添加「|安全」如下:

{% for i in myList %} 
    <tr> 
    <a href= " {{ urls[i[0]] | safe }} "> 
     <td> 
     {{ i[0] }} 
     </td> 
    </a> 
    </tr> 
    {% endfor %} 
+0

謝謝你的回答,但它不起作用,和以前一樣 – accand