Jinja2:使用pandas数据帧或字符串变量

2024-04-24 23:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我从jinja2模板得到了意外的输出。在

我有一个实例,其中一个表要么用单个值填充,要么用一组值填充。每个模板的表示都有点不同,所以我想我可以用一个条件{% if my_variable is mapping %}检查模板变量的状态,然后继续执行我的模板代码。 以下是我的模板代码:

<table class="summary_table halfpage">
           <thead>
               <tr>
                 <th>
                     My Table
                 </th>
               </tr>
           </thead>
           <tbody>
           {% if my_variable is mapping %}
               {% for key,value in my_variable.iterrows() %}
                   <tr>
                     <td>
                       <p><strong>{{ value['Column1'] }} : </strong> {{ value['Column2'] }}</p>
                     </td>
                   </tr>
               {% endfor %}
            {% else %}
                  <tr>
                    <td>
                      <p><strong>{{ my_variable }}</strong></p>
                    </td>
                  </tr>
            {% endif %}
           </tbody>
       </table>

当我的_变量是一个字符串(即不是一个映射)时,这很好用。但是当它是一个映射时,我得到的不是一个很好地呈现的表:

^{pr2}$

以下是生成模板变量并将其加载到模板中的python代码:

def load_data(data_name, grade=None):
    file_path = os.path.join(data_path, for_who + "_" + when + "_" + data_name + ".csv")
    if not os.path.isfile(file_path):
        file_path = False   
    if file_path:
        data = pd.read_csv(file_path)
    else:
        data = False
    return data

def make_my_variable():
    data = load_data("relevant_data") 
    if not isinstance(data, pd.DataFrame):
        data = load_data("other_relevent_data")
        #in the case of "other_relevent_data" the column names are different
        data = data["ColumnA"].iloc[0]
    return data

report = report_tmpl.render(
    my_variable = make_my_variable()
)

html_output = os.path.join(output_path, for_who + "_" + date_transform(when) + ".html")
with open(html_output, 'w') as fh:
    fh.write(report)

你知道我做错什么了吗?如果他不带条件的话,这就很好了。在

编辑:添加了python代码,用于创建my_变量并呈现模板


Tags: path代码模板fordataifvaluemy
1条回答
网友
1楼 · 发布于 2024-04-24 23:24:28

多亏了@moooeeep我才得以解决这个问题。正如他提到的,问题来自于pd数据帧在jinja2中不被识别为映射。所以,我把我的数据帧转换成了一个列表:

def make_my_variable():
    data = load_data("relevant_data") 
    if not isinstance(data, pd.DataFrame):
        data = load_data("other_relevent_data")
        #in the case of "other_relevent_data" the column names are different
        data = data["ColumnA"].iloc[0]
    else:
        data = [(v["Column1"], v["Column2"]) for k,v in data .iterrows()]
    return data

在模板方面,我将条件改为:

^{pr2}$

收件人:

{% if most_popular_games is iterable and my_variable is not string %}
    {% for value in my_variable %}
#and..
<p><strong>{{ value[0] }} grade:</strong> {{ value[1] }}</p>

总而言之,最终的模板代码如下所示:

<table class="summary_table halfpage">
           <thead>
               <tr>
                 <th>
                     My Table
                 </th>
               </tr>
           </thead>
           <tbody>
           {% if my_variable is iterable and my_variable is not string %}
               {% for value in my_variable %}
                   <tr>
                     <td>
                       <p><strong>{{ value[0] }} : </strong> {{ value[1] }}</p>
                     </td>
                   </tr>
               {% endfor %}
            {% else %}
                  <tr>
                    <td>
                      <p><strong>{{ my_variable }}</strong></p>
                    </td>
                  </tr>
            {% endif %}
           </tbody>
       </table>

相关问题 更多 >