简体   繁体   English

Django 模板 - 如何检查动态构造的键是否在对象中具有值

[英]Django Template - How to check if dynamically constructed key has value in Object

I've an object that contains names like我有一个包含名称的对象

draft = {
  "name_ar": "test arabic",
  "name_en": "test english",
  "name_tr": "test turkish",
  "name_nl": "",
}

and I've language_code variable which will have either 'ar' or 'en' values.我有language_code变量,它将具有“ar”或“en”值。 So before checking if key has value in the object what I did is I constructed the key first like below因此,在检查对象中的键是否具有值之前,我所做的是首先构造键,如下所示

{% with name='name_'|add:language_code %}

So now my query is I want to add class grey-color to div container if name doesn't have value in draft object.所以现在我的查询是如果名称在draft对象中没有值,我想将类grey-color添加到 div 容器。 How can I achieve this?我怎样才能做到这一点?

{% with name='name_'|add:language_code %}
   <span class="secondary-title {% if not "how can I check here" %}grey-color{% endif %}">
{% endif %}

I'm very new to Django so happy to hear any suggestions or solution.我对 Django 很陌生,很高兴听到任何建议或解决方案。

I solved the issue using template tags我使用模板标签解决了这个问题

@register.filter('get_value_from_dict')
def get_value_from_dict(dict_data, key):
    """
    usage example {{ your_dict|get_value_from_dict:your_key }}
    """
    if key:
        return dict_data.get(key)

and then in template然后在模板中

<span class="secondary-title {% if not draft|get_value_from_dict:name %}grey-color{% endif %}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查迭代的内容是否是字典中的最后一个键/值? (可能需要在Django模板中完成) - How to check if that which is iterated upon is the last key/value in a dict? (probably needs to be done in django template) 如何获取django模板中的键值? - How to get key value in django template? 如何在Django模板中获取字典的键值 - how to get the key value of a dictionary in django template 如何将外键值显示到模板 django - how to display foreign key value to template django 如何检查对象是否在 Django 中具有属性? - How to check if the object has property in view in Django? Django模板外键检查 - Django Template Foreign Key Check 在字典中,如何检查一个键是否正好有 1 个值? - In a dictionnary, how to check that a key has exactly 1 value? 在 django 查询集过滤器中,如何检查 json 字段中是否至少有一个键具有非空值? - In django queryset filter, how to check if at least one key in json field has non empty value? 如何检查表对象中字段的值是否等于 Django 模板语言中的特定字符串? - How to check if value from a field in a table object is equal to specific string in django template language? 如何检查键是否在 django 模板的字典中? - How can I check if a key is in a dictionary on a django template?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM