简体   繁体   English

在Django模板循环中包含变量

[英]Include variable in Django template loop

I have a for loop in a Django template, which prints out a list of books, which works well. 我在Django模板中有一个for循环,它可以打印出一本好书。 The issue comes when I try to mark one of the items in the list as selected, based on a value passed in from the views.py file: 当我尝试根据从views.py文件传入的值将列表中的一项标记为选中时,就会出现问题:

<select name="b">
    <option value="1">Book</option>
    {% for book in books %}
        <option {% if book.id == selected_book %} selected {% endif %} value="{{ book.id }}">{{ book.t }}</option>
    {% endfor %}
</select>

The "books" variable is a list, passed in from the views.py file. “ books”变量是一个列表,从views.py文件传入。 I can access these variables fine outside of the loop, but if I try to include a seperate variable inside the loop ("selected_book"), I have issues. 我可以在循环外部很好地访问这些变量,但是如果尝试在循环内部包括一个单独的变量(“ selected_book”),则会遇到问题。

The above code does nothing, and if I try to wrap the variable in double brackets 上面的代码没有任何作用,如果我尝试将变量包装在双括号中,

{{ selected_book }}

I get the following error: 我收到以下错误:

TemplateSyntaxError 
Could not parse the remainder: '{{' from '{{'

The variable is being passed into the template, because I can get it to print to the page. 该变量被传递到模板中,因为我可以将其打印到页面上。 I only get an error when I try to use it in the for loop. 当我尝试在for循环中使用它时,只会出现错误。

If I write "{% if book.id == 2 %}" that works fine. 如果我写“ {%if book.id == 2%}”,那很好。

确保selected_book是整数而不是字符串,否则代码很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM