I am trying to render html template with Jinja2 - putting in variable values, which are extracted from Pandas dataframes. Currently I have variables hardcoded into render command, as seen below:
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])
Issue is that sometimes, there is no 3rd row in "play" dataframe, which returns an index error (as there are no elements there).
I have created a loop to prepare variable, which could be inserted into render command, as shown below:
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)
With this, I recieve following error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I presume reason behind it is that I have created a string, which can not be used in Jinja2 render command. Any idea if there is possibility to pass string to that command or do I have to find another way to address issue of extracting elements based on Dataframe size?
Thank you and best regards, Bostjan