Dhruv Shekhawat Dhruv Shekhawat - 23 days ago 9
HTML Question

Unable to access list elements from Flask template variables in JavaScript

I have a function in JavaScript

function functioncalled(){
var result = 1;
var activityID = {{ mynames[result][8] }};
console.log(activityID);


}

mynames is a list of lists in Flask template. The above code fails giving me an error - UndefinedError: list object has no element Undefined. But when I access the list element using
var activityId = {{mynames[1][8]}}
everything works fine. How do I make this work? Is there a workaround? I couldn't find the solution anywhere.

Answer

You will not be able to do that, because {{any_flask_variable}}is evaluated on server side and rendered HTML is sent to browser where all javascript runs. At the time of evaluation on the server there is not browser to run javascript code. The best way to resolve this is to assign the list variable to var result.

function functioncalled(){
var result = {{mynames}};
// Here you can access the variable result
console.log(activityID);
}

That off course after assuming that mynames variable can be mapped to js array of arrays.

Comments