2đź‘Ť
Django’s template rendering just do a search/replace sort of substitution:
it gets the string inside the curly braces – and use that string as a key int he dictionary is passed to it.
It does not try to access the dictionary values as data structures – instead, it will simply take it string representations.
So,
data = {"variable": ["a", "b", "c"] }
Can be retrieved inside the dtemplate witht he name “variable” – but the rendering template should raise a NameError if you try to access “variable[0]” – simply because “variable[0]” is not a key on the data dictionary above.
One way to deal with it is to defer the indexing part to javascript code, on the client, and pass javascript encoded (json) strings of the objects on the data dictionary – so you would do something along:
import json
function changeDate()
id = 5
variable = ["bla", "ble", "bli", "blo", "blu", "blew"]
html = """<script> id = {{id}};
document.write({{variable}}[id]);
</script>
"""
data = {"variable": json.dumps(variable), "id": id};
and pass this data to be rendered with the html
template.