Flask表格无法渲染HTML标签(如<br>)的问题求助
解决HTML表格中
<br>标签显示为文本而非换行的问题 问题根源有两点:
- pandas的
to_html()方法默认会转义HTML特殊字符,把<br>转换成<br>,导致浏览器将其识别为文本而非换行标签 - 你的产品描述中使用的是转义后的
<br>,而非原生HTML换行标签
修复步骤:
- 替换换行标签格式:把描述里的
<br>改成原生的<br>标签 - 关闭pandas的HTML转义:调用
to_html()时添加escape=False参数,保留HTML标签的原始格式
修改后的Python代码:
import pandas as pd from flask import Flask, render_template, abort, url_for, Markup import json from json2html import Json2Html app = Flask(__name__) @app.route('/') def index(): # 使用原生<br>标签实现换行 desc1 = "This is an amazing product. <br> It will change your life forever. <br> In ways you can not imagine" desc2 = "This product will change your life. <br> Although we can't say for good or for bad. <br> It can either turn your life in heaven, or hell" table = pd.DataFrame({"Desc1":[desc1], "Desc2":[desc2]}) # 添加escape=False,禁止pandas转义HTML标签 table = table.to_html(index=False, escape=False) return render_template('inde.html', table=table)
效果说明:
修改后,pandas生成的HTML表格会保留<br>标签的原始格式,配合Flask模板中的{{ table | safe }},浏览器就能正确解析换行标签,实现文本换行的效果。
内容的提问来源于stack exchange,提问作者Sudhanshu Singh
相关产品推荐
相关产品推荐

