问题
I have a weird situation where array has value as None:
'synonyms': [None]
The json format of data in mongo is as:
{
"_id": {
"$oid": "5e0983a63bcf0dab51f32a9d"
},
"word": "vulgarizer",
"wordset_id": "c0c349060a",
"labels": [{
"name": "American",
"is_dialect": true
}],
"meanings": [{
"id": "3cb39b55e5",
"def": "someone who makes attractive to the general public",
"speech_part": "noun",
"synonyms": ["populariser"]
}, {
"id": "865bfdea0b",
"def": "someone who makes something vulgar",
"speech_part": "noun",
"synonyms": [null]
}],
"editors": ["lefurjah"],
"contributors": ["luxfactaest", "msingle", "bryanedu"]
}
But when I tried printing the same in python it showed up as:
'meanings': [{
'id': '3cb39b55e5',
'def': 'someone who makes attractive to the general public',
'speech_part': 'noun',
'synonyms': ['populariser']
}, {
'id': '865bfdea0b',
'def': 'someone who makes something vulgar',
'speech_part': 'noun',
'synonyms': [None]
}]
How do I check this value in if
condition :
I have tried as:
{% if meaning['synonyms'] is defined and meaning['synonyms']|length > 0 %}
do something-- if condition matches
But the None in array doesn't refer to a null value ?
Any possible solution? TIA
回答1:
You can use in
condition inside jinja
(as in Python).
from jinja2 import Template
data = {"synonyms": [None], "synonyms2": ['ok']}
tm = Template(
"None in synonyms: {{ None in data['synonyms'] }}\n"
"None in synonyms2: {{ None in data['synonyms2'] }}\n"
"{% if None in data['synonyms'] %}None in synonyms {% endif %}\n"
"{% if None in data['synonyms2'] %}None in synonyms2 {% endif %}\n"
)
msg = tm.render(data=data)
print(msg)
Result:
None in synonyms: True
None in synonyms2: False
None in synonyms
Hope this helps.
来源:https://stackoverflow.com/questions/59665771/check-for-none-in-an-array-in-flask-jinja-template