我正在尝试使用 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: dictionary update sequence element #0 has length 1; 2 is required
我推测其背后的原因是我创建了一个字符串,它不能在 Jinja2 render 命令中使用。知道是否有可能将字符串传递给该命令,或者我是否必须找到另一种方法来解决基于 Dataframe 大小提取元素的问题?
谢谢你和最好的问候, 博斯扬
请您参考如下方法:
我做了一些挖掘并提出了解决方案。我将其张贴在这里以防其他人遇到类似问题。 正如预期的那样,问题是它是单个字符串。所以最初我准备了相同的字符串(更改为“,”,“|”作为分隔符,因为“,”也包含在 iat 命令中)。然后我用字符串创建了字典并在 template.render() 中使用它。 下面是代码:
template_variables = "reg=" + str(reg.iat[0, 0]) + "|ac=" + str(ac.iat[0, 0]) + "|su_new=" + str(su_new.iat[0, 0]) + "|chu_new=" + str(chu_new.iat[0, 0]) + "|"
for i in range(play.shape[0]):
template_variables += "title_" + str(i) + "=" + str(play.iat[i, 0]) + "|title_" + str(i) + "_count=" + str(play.iat[i, 1]) + "|"
template_variables = template_variables.rstrip("|")
template_variables = dict(map(lambda variable: variable.split('='), template_variables.split('|')))
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)
这可能不是最优雅的做法,但它似乎可以解决问题。
最好的问候, 博斯扬
