3

I have one static dictionary:

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

Then I have a list of tuples. Each tuple contains one key of the previous dictionary:

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

I want to put in my template the related url for each key string in the descending order as they are in the list (created in this way obviously with the reverse = True set).

In the template I have tried this, but, as expected, it doesn't work:

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

So, how can I access the dictionary elements?

Community
  • 1
  • 1
accand
  • 531
  • 1
  • 8
  • 17

2 Answers2

1

Your resulting HTML is wrong.

Don't put table elements into your link text the way you do it.

I've tested plain html like this:

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

and it will result in a "dead" link. Put the full a href into your <td> instead:

<table>
  <tr>
    <td> 
      <a href= " http://google.de ">
        Fooo 
      </a>
    </td>
  </tr>
</table>
ferdy
  • 7,366
  • 3
  • 35
  • 46
  • 2
    About as useful as "The code you said doesn't work? It doesn't work." – Adam Smith Nov 03 '15 at 16:38
  • Hi, my mistake, your solution is right. But I did not downvote you, as a matter of fact I have not enough reputation. Checkmark for you instead – accand Nov 03 '15 at 16:49
  • No, all is fine with you. It was @AdamSmith who is quite fast downvoting someone despite he is actually refining his answer though. Nevermind... I shouldn't have answered incompletely in the first run not to be bashed. – ferdy Nov 03 '15 at 16:52
  • @ferdy well you answered, then deleted, then edited your deleted answer, then undeleted, then FURTHER edited into a *real* answer. I've now removed my downvote. – Adam Smith Nov 03 '15 at 17:18
  • @AdamSmith, thank you. Well, I edited the deleted answer because the system said I should preferably edit the old answer instead of creating a new one. So, because in the first answer I got the question completely wrong, I didn't want to have it on the screen for too long, so I did a preview of the final answer. That was the "genesis" of this thing. All right now. – ferdy Nov 03 '15 at 18:11
0

You need to add "| safe " as follows:

    {% for i in myList %}
    <tr>
    <a href= " {{ urls[i[0]] | safe }} ">  
      <td>
        {{ i[0] }}
      </td> 
    </a> 
    </tr>
    {% endfor %} 
jodoox
  • 821
  • 2
  • 7
  • 22