开发者

Django template: Ordering dictionary items for display

I am making a website that displays a user's chosen youtube videos. A user can enter a comment for each video.

I want to display (in this order):

  1. User comment

  2. video title

I have already made the view and have created the following list of dictionary items. Each one represents one video. I send this to my html page:

[
    {"my_own_object": vid_obj1, "youtube_obj": obj1} 
    {"my_own_object": vid_obj2, "youtube_obj": obj2}
]

"youtube_obj" is the object supplied by youtube, which contains the url, title, rating, etc. "my_own_object" contains the user's comments as well as other information.

I iterate over the list and get one dictionary/video. That's fine. Then I need to display the video's information:

{% for key,value in list.items %}

   开发者_如何学Python{% if key = "my_own_object" %}
       <div>
       <p>{{value.user_comment}}</p> 
      </div>  
   {% endif %}  
   {% if key = "youtube_obj" %}
       <div>
       <p> {{value.media.title.text}}</p> 
      </div>  
   {% endif %}                  
{% endfor %}

This works, except that, because I cannot determine the dictionary order, I might end up with:

  1. Video title

  2. User comment

I thought I could get around this by assigning variables (and then printing the values in the proper order), and am still reeling from the fact that I cannot assign variables!

So, how can I get around this? Can I pluck the key/value that I need instead of iterating over the dictionary items - I tried looking for ways to do this, but no luck. Any other ideas? (I need to pass both video objects as I may need more information than comment and title, later.)


You can use dictionary keys directly:

{% for item in list %} {# PS: don't use list as a variable name #}
    <p>{{item.my_own_object.user_comment}}</p>
    <p>{{item.youtube_obj.media.title.text}}</p>
{% endfor %}


Just iterate twice. Once for the videos, and once again for the comments. Or, split them into their own dictionaries that are passed through to the template. That's probably a better option, as you avoid iterating twice over the dict. For very small dicts this will be no problem. For larger ones, it can be a problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜