I can’t seem to figure this one out. I’ve got a Python/Django template which renders my variables using {{ variable }} and I’m trying to use Javascript on the HTML page to manipulate the variable when the user clicks a button.
The problem I’m seeing is that Javascript seems to treat {{ differently, so that when it renders as HTML, it doesn’t convert the variable (ie. it shows “+ id + ” instead of 5 from the code below:
function changeDate()
id = 5;
html = "{{ variable[" + id + "] }}";
document.getElementById('test').innerHTML = html;
I’ve tried escaping them like this: “{{” and that seems to work (ie. it converts ‘id’ to 5) but then Python doesn’t interpret the string as a variable and it just displays the string on the page as {{ variable[5] }} rather than the real value of that variable.
My guess is that this happens because Javascript is converting the DIV to the new text after the page is already rendered, so Python never has the chance to convert the variable when it first renders the page.
So I think there are two possible solutions:
- Figure out a way to render the variable properly while leaving the {{ and }} in the string
or
- Figure out how to get Python to interpret the string version of {{ variable[5] }} before it’s ever displayed through Javascript.
Any help is appreciated!
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,
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:
and pass this data to be rendered with the
htmltemplate.