python - 区分jinja2中的类型

标签 python html python-3.x flask jinja2

我有一个 HTML/jinja2 模板,用于以表格形式显示数据。

表的数据可能以不同的方式出现,我希望模板能够使用 if 语句处理这两种类型。 python 中的 type(x) 函数在此语言中不起作用。

  1. 字典数组(字典列表)

  2. 数组的数组(列表的列表)

模板的一部分:

{% block page_content %}
<input type="text" id="search" placeholder="Type to search">
<table id="table" class="table">
<tr style="white-space:nowrap;">
    {% for h in headers %}
    {% if h is string %}
    <th>{{h}}</th>
    {% else %}
    <th>{{h[1]}}</th>
    {% endif %}
    {% endfor %}
</tr>
{%if data is "TYPE CHECK HERE"}
{% for row in data %}
{% if row != {} %} #ALTERNATIVELY, COULD DO A TYPE CHECK HERE
<tr style="white-space:nowrap;{% if row['bad'] %}background-color:rgba(255, 0, 0, 0.09);{% endif %}">
    {% for h in headers %}
    <td style="white-space:nowrap;">{{ row[h[0]] }}</td>
    {% endfor %}
</tr>
{% endif %}
{% endfor %}

{% 结束 block %}

TL:DR jinja2 中有哪些可区分的类型?如何检查变量的类型?

最佳答案

在渲染 jinja 之前,最好将尽可能多的逻辑代码保留在 python 端。

因此,将 python 端的数据传输到 header 列表,并将嵌套列表作为数据:

render_template('test.html', 
                headers=['name', 'age',], 
                rows=[{'color': 'red', 'data': ['john', 84]},
                      {'color': 'green', 'data':['jacob', 45]}]

html:

 <table>
  <thead>
    <tr>
    {% for item in header %}
      <th> {{ item }} </th>
    {% endfor %}
    </tr>
  </thead>

  <tbody>
  {% for row in rows %}
    <tr style="colour: {{ row['color'] }}">
    {% for cell in row['data'] %}
      <td>{{cell}}</td>
    {% endfor %}
    </tr>
  {% endfor %}
  </tbody>
</table>

我在学习时也尝试过与您类似的方法,但最终我发现这种方法效果最好,因为它为您提供了对数据的最大灵 active ,并且在 python 端操作数据通常非常简单。所以这并不是一个真正的答案,只是一般建议。

关于python - 区分jinja2中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49887289/

相关文章:

python - wxpython 在 wx.Frame 中捕获键盘事件

javascript - 鼠标悬停问题

html - 如何在不发生换行的情况下将按钮放入文本中?

javascript - 切换 div 的宽度时如何保持内部元素的位置?

python - 在 python pandas 中将多个年份列转换为单个年份列(整洁格式)

python - 如何使用 Jinja2 打印表格(无需页面刷新)

python - Django - 在无效表单提交中保存字段

python - 转换 DataFrame 中的每个组

python-3.x - 属性错误: 'str' object has no attribute 'flow_from_directory'

python-3.x - 加速 Keras LSTM