Issue
I have the following code to generate html from pandas dataframe. I'm using JS to access each table row but getting an error.
File "<fstring>", line 2
var elem = array[i].cells[1].innerHTML;
^
SyntaxError: invalid syntax
def generate_html_main_page(dataframe: pd.DataFrame):
# get the table HTML from the dataframe
table_html = dataframe.to_html(table_id="table")
# construct the complete HTML with jQuery Data tables
html = f"""
<html>
<header>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet">
</header>
<body>
{table_html}
<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var array = document.getElementById("table").rows
for (let i = 0; i < array.length; ++i) {
var elem = array[i].cells[1].innerHTML;
document.getElementById("table").rows[i].cells[1].innerHTML = "<a href='#test'>" + elem +"</a>"
document.write(document.getElementById("table").rows[i].cells[1].innerHTML)
}
</script>
</body>
</html>
"""
# return the html
return html
Any pointers are greatly appreciated. Thanks!
Solution
You're using an f-string to generate HTML, but the HTML also has {
/}
characters in it. So Python is trying to execute the body of your JavaScript for
loop as Python code.
You can escape them as {{
/}}
when you want them to just be literal braces. Or use plain string concatenation (html = '''...''' + table_html + '''...'''
).
Answered By - bobince
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.