英文:
Accessing HTML table row element from pandas dataframe
问题
以下是代码的翻译部分:
def generate_html_main_page(dataframe: pd.DataFrame):
# 从数据框中获取表格的HTML
table_html = dataframe.to_html(table_id="table")
# 构建包含jQuery数据表格的完整HTML
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>
"""
# 返回HTML
return html
希望这对你有帮助!
英文:
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!
答案1
得分: 0
您正在使用 f-string 生成HTML,但HTML中还包含{
/}
字符。因此,Python尝试将您的JavaScript for
循环的主体作为Python代码执行。
当您希望它们只是字面大括号时,您可以将它们转义为{{
/}}
。或者使用普通的字符串连接(html = '''...''' + table_html + '''...'''
)。
英文:
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 + '''...'''
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论