In django templates, can I select a specific < option > based on its index?
That is, I have a template as with an such:
<select>
<option val='fs-1'>Foo</option>
<option val='fs-2'>Bar</option>
... (Many more options> ...
</select>
When I am rendering the template, I know what is the index of the item I want selected.
I know I can do this in a way that’s described here but I have many < select > tags with lots of options, and this is not an efficient way of doing this.
It’s not clear when you know what index should be selected or how you determine that from your question, so it’s impossible to tell you which way is best. However, in total, there’s only three ways to set it:
Specify an initial value on the form:
The method you linked to, that you don’t want to do (cycling through the options and printing
selected="selected"if the value matches)Use JavaScript (jQuery used for illustration):