{%if v1 == v2%}在Django模板中不适用于我,其中v1是来自查询集的值,而v2是我从上下文获得的值

问题描述:

我有一个ID传递给我的模板,也通过列表循环来产生选择块的选项。我想在匹配的值上添加selected ='selected',但它看起来像django模板不允许我比较if子句中的值。我怎么能这样做{%if v1 == v2%}在Django模板中不适用于我,其中v1是来自查询集的值,而v2是我从上下文获得的值

我使用1.3,我试过如果v1 == v2,也试过ifequal v1 v2。

 {% for h in hotel_list %} 
    <option value="{{ h.HotelId }}" {% if h.HotelId == request.hotel_id %}selected="selected"{% endif %}>{{ h.Title }}</option> 
    --{{h.HotelId}}--{{request.hotel_id}}-- 
    {% endfor %} 

这是我如何调用模板:

return render_to_response('hotels/select_hotel.html', {'hotel_list': all_hotels, 'request' : request.GET}) 

这就是我得到:

<select id ='hotel_id' name = 'hotel_id'> 


    <option value="2" >Holiday Inn</option> 

    --2--7-- 

    <option value="3" >Joel&#39;s Inn</option> 

    --3--7-- 

    <option value="6" >Joel&#39;s Joint</option> 

    --6--7-- 

    <option value="1" >The Paris Hilton</option> 

    --1--7-- 

    <option value="7" >Waldorf Astoria</option> 

    --7--7-- 

</select> 
+0

我说有问题的模板片段。我比较两个变量而不是一个字符串文字的变量。我想知道这是不是被允许的? – 2011-12-19 19:08:47

因为它结束了我是一个字符串比较int。事实证明,

response.GET['hotel_id'] 

是一个字符串,所以我转换为int,并通过它沿背景下我的表单

做V1 V2 = =应根据Django文档是正确的。

==操作符

平等。例如:

{% if somevar == "x" %} 
    This appears if variable somevar equals the string "x" 
{% endif %} 

我得到这个从https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#operator

,如果你发布你的代码会更容易帮助。