Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django模板中类似开关条件的更好语法_Django_Django Templates - Fatal编程技术网

Django模板中类似开关条件的更好语法

Django模板中类似开关条件的更好语法,django,django-templates,Django,Django Templates,有人知道在Django模板中执行类似于开关的评估的方法比下面的方法要简单吗 <div class="alert {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}alert-danger {% elif message.level == DEFAULT_MESSAGE_LEVELS.WARNING %}alert-warning {% elif message.

有人知道在Django模板中执行类似于开关的评估的方法比下面的方法要简单吗

<div class="alert {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}alert-danger
                  {% elif message.level == DEFAULT_MESSAGE_LEVELS.WARNING %}alert-warning
                  {% elif message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}alert-success
                  {% elif message.level == DEFAULT_MESSAGE_LEVELS.INFO %}alert-info
                  {% elif message.level == DEFAULT_MESSAGE_LEVELS.DEBUG %}alert-dark
                  {% else %}alert-light{% endif %} alert-dismissible fade show" role="alert">
  {{ message }}
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

{{message}}
&时代;
创建并将
级别作为参数传递。像这样的

#yourapp/templatetags/message_level.py
从django导入模板
#导入您的默认\u消息\u级别
register=template.Library()
@register.simple_标记
def get_消息_css_级别(级别):
''根据消息级别''返回标记的类名'
如果级别==默认消息级别。错误:
返回“危险”
elif级别==默认消息级别。警告:
返回“警告”
elif级别==默认消息级别。成功:
返回“成功”
elif level==默认消息级别。信息:
返回“信息”
elif level==默认消息级别。调试:
返回“黑暗”
其他:
返回“光”
另外,在
模板标签
中创建一个空的
\uuuu init\uuuuuuuuupy.py
文件,这一点很重要。然后在
模板中添加新的自定义模板标记:

{%loadmessage\u level%}
{{message}}
&时代;