如何通过数据中键的值来检查条件,并在存在的情况下显示所有嵌套值

2024-10-07 16:28:44 发布

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

我有mongo文档数据示例(供参考):

The <code>data</code> object passed to the template is as this

从视图为:

data=wordscollection.find({'word':word})
return render_template('wordsearch.html',data=data)

在模板中,我仅将其作为第一个索引,不检查示例或同义词是否为空:

{% for word in data %}
    <tr>Meaning :{{  word['meanings'][0]['def'] }}</tr><br>
    <tr>Example :{{  word['meanings'][0]['example'] }}</tr><br>
    <tr>Parts Of Speech :{{  word['meanings'][0]['speech_part'] }}</tr>
{% endfor %}

输出为:

enter image description here

1)如何将所有索引结果显示为

meaning1: def1
speechpart1: speech_part1
example1:                    //2)writing condition for this to show if exits
synonym:                      //2)writing condition for this to show if exits

Meaning2: def2
........
........

我试了两次运气如下:

      {% for word in data if word['meanings'][0]['example'] %}

但这也不管用

谢谢你的帮助,蒂亚


Tags: toinbr示例fordataifexample
2条回答

同义词更新答案

    {% for word in data %}
        {% for meaning in word['meanings'] %}

                <tr>Meaning :{{  meaning['def'] }}</tr><br>

                {% if meaning['example'] %}
                    <tr>Example :{{  meaning['example'] }}</tr><br>
                {% endif %}

                {% if meaning['speech_part'] %}
                    <tr>Parts Of Speech :{{  meaning['speech_part'] }}</tr><br>
                {% endif %}
                 {% for synonyms in meaning['synonyms'] %}
                        {% if meaning['synonyms'] %}
                            <tr>synonyms : {{ synonyms }} </tr><br>
                        {% endif %}
                 {% endfor %}
        {% endfor %}
    {% endfor %}

您还必须使用嵌套for循环来迭代meanings,并在之前检查空值

{% for word in data %}
    {% for meaning in word['meanings'] %}
        <tr>Meaning :{{  meaning['def'] }}</tr><br>
        {% if meaning['example'] %}
            <tr>Example :{{  meaning['example'] }}</tr><br>
        {% endif %}
        {% if meaning['speech_part'] %}
            <tr>Parts Of Speech :{{  meaning['speech_part'] }}</tr>
        {% endif %}
    {% endfor %}
{% endfor %}

相关问题 更多 >