Home > Net >  Dynamically loop python list in Javascript
Dynamically loop python list in Javascript

Time:10-18

I'm facing the issue when passing list from Python to Javascript. I need to loop the python list in javascript to get each element of the list. So, could you please help me out with how to dynamically loop the list to get all the values from the df or is there any other way to achieve it.

Below is the code: .PY file:

df = pd.read_csv('os.csv')
df = df.fillna('-')
df = df.values.tolist()
return render_template('pdf_test.html',df = df)

python output: df = [['OS Version', 'Red Hat Enterprise Linux Server 7.6 (Maipo)'], ['OS Kernel Version', '3.10.0-957.97.1.el7.x86_64']]

Javascript

<script type="text/javascript">
    function saveDiv() 
    {
        var df1 = '{{df[0]}}'; //it returns first index of the list.How to dynamically loop the list to get all the values from the df.
    }
</script>

CodePudding user response:

Sorry, not enough reputation for comment, hence posting as answer.

When you pass List to JS code, you need to print it out as encoded, usually in PHP we do with json_encode,

I looked for the similar and found for python as well.

 json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})

'{"pear": "fish", "apple": "cat", "banana": "dog"}'

I think with this you can print your JSON, and JS will recognize it as Array. Further you can perform JS operations.

Source: https://stackoverflow.com/a/983879/20164098

CodePudding user response:

Can you get DOM in JavaScript?
If you could, just generate a string with df and insert the dom.
For example: if there's a dom in your HTML:

<div id='listBlock'></div>

generate dom string with javascript:

const domString = df.map(i => `<div class='list-item'>${i}</div>`)
const listDom = document.getElementById('listBlock')
listDom.appendChild(domString)
  • Related