2013-11-02 63 views
29

我將我的視圖中的字典傳遞給模板。所以{"key1":"value1","key2":"value2"}被傳入並循環通過鍵,值對是好的,但我還沒有找到一個優雅的解決方案直接從視圖中訪問特定的鍵,例如"key1"例如bu json.items [「key1」]。我可以使用一些if/then語句,但我寧願直接做有沒有辦法?通過Django模板中的鍵訪問字典

下面是在HTML模板循環代碼:

{% for key, value in json.items %} 
    <li>{{key}} - {{value}}</li> 
{% endfor %} 

回答

49

Django模板語言支持查找字典項,如下所示:

{{ json.key1 }} 

參見variables and lookups模板文檔。

模板語言不提供顯示​​的方法,其中key是一個變量。您可以編寫模板過濾器來執行此操作,如Stack Overflow question的答案中所述。

4

爲了克服這個問題,你可以嘗試這樣的事:

def get_context_data(self, **kwargs): 
    context['cart'] = [] 
    cart = Cart() 
    cart.name = book.name 
    cart.author = book.author.name 
    cart.publisher = book.publisher.name 
    cart.price = 123 
    cart.discount = 12 
    cart.total = 100 
    context['cart'].append(cart) 
    return context 


class Cart(object): 
    """ 
    Cart Template class 

    This is a magic class, having attributes 
    name, author, publisher, price, discount, total, image 
    You can add other attributes on the fly 
    """ 
    pass 


By this way you can access your cart something like this: 
{% for item in cart %} 
    <div class="jumbotron"> 
    <div> 
    <img src="{{item.image}}" /> 
    <div class="book_name"> <b>{{item.name}}</b></div> 
    <div class="book_by"><i>{{item.author}}</i></div> 
    <span>Rs. {{item.price}}</span> <i>{{item.discount}}% OFF </i> 
    <b>Rs. {{item.total}}</b> 
{% endfor %} 
3

例如,發送下面字典 dict = {'name':'myname','number':'mynumber'}

觀點: return render(request, self.template_name, {'dict': dict})

要渲染HTML中的價值模板: <p>{{ dict.name }}</p>

它打印'myname'