【发布时间】:2018-07-29 15:46:53
【问题描述】:
我正在尝试使用 Jinja2 呈现 html 模板 - 放入从 Pandas 数据帧中提取的变量值。目前我将变量硬编码到render 命令中,如下所示:
template_loader = jinja2.FileSystemLoader(searchpath=template_dir)
template_env = jinja2.Environment(loader=template_loader)
template_file = "report.html"
template = template_env.get_template(template_file)
html_code = template.render(reg=reg.iat[0, 0], ac=ac.iat[0, 0],
su_new=su_new.iat[0, 0], chu_new=chu_new.iat[0, 0],
title_0=play.iat[0, 0], title_0_count=play.iat[0, 1],
title_1=play.iat[1, 0], title_1_count=play.iat[1, 1],
title_2=play.iat[2, 0], title_2_count=play.iat[2, 1])
问题是有时,“播放”数据帧中没有第 3 行,这会返回索引错误(因为那里没有元素)。
我已经创建了一个循环来准备变量,可以将其插入到render命令中,如下所示:
template_variables = "reg=reg.iat[0, 0], ac=ac.iat[0, 0],su_new=su_new.iat[0, 0], chu_new=chu_new.iat[0, 0], "
for i in range(play.shape[0]):
template_variables += str("title_" + str(i) + "=play.iat[" + str(i) + ", 0], title_" + str(i) + "_count=play.iat[" + str(i) + ", 1], ")
template_variables = template_variables.rstrip(", ")
template_loader = jinja2.FileSystemLoader(searchpath=template_dir)
template_env = jinja2.Environment(loader=template_loader)
template_file = "report.html"
template = template_env.get_template(template_file)
html_code = template.render(template_variables)
这样,我收到以下错误:
ValueError: 字典更新序列元素#0 的长度为 1; 2 是必需的
我想这背后的原因是我创建了一个字符串,它不能在 Jinja2 render 命令中使用。知道是否有可能将字符串传递给该命令,或者我是否必须找到另一种方法来解决基于 Dataframe 大小提取元素的问题?
谢谢你和最好的问候, 博斯扬
【问题讨论】:
标签: python templates jinja2 render