如何使用Django中的if语句编写更好的模板逻辑? [英] How do I write better template logic with if statements in Django?

查看:122
本文介绍了如何使用Django中的if语句编写更好的模板逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Django模板中写得更有效率,这样就不会是一个巨大的if语句?我想禁用一个元素到request.path中的所有页面和一些页面的一些例外。这是我到目前为止

  {%if/ create-account /in request.path或/ lists / request.path中的request.path或request.path中的/ contact-us /或request.path%中的/ news /
{%else%}
{%include'includes / element。 html'%}
{%endif%}

必须有更好的方法。



在X,Y或Z之外的所有页面上显示此元素。

解决方案

我可以想到的最短的时间是在需要显示的那些url的上下文数据中包含一个上下文变量它

 #views 
{'ignore_element':':)'}

#模板
{%if not ignore_element%}
{%include'includes / element.html'%}
{%endif%}
pre>

这将工作,因为它只为那些不包括这个上下文值的人显示。



任何更好的解决方案将取决于为什么这4个应该免除显示的逻辑背后


How can I write this more efficient in Django templates so it won't be a huge if statement? I want to disable an element to ALL pages in request.path and some exceptions for some pages. This is what I got so far

{% if "/create-account/" in request.path or "/lists/" in request.path or "/contact-us/" in request.path or "/news/" in request.path %}
{% else %}
    {% include 'includes/element.html' %}
{% endif %}

There must be a better way. To clarify my needs:

Display this element on all pages except X, Y or Z.

解决方案

The shortest way I can think of at the minute is to include a context variable in the context data for those urls that do need to show it

# views
{ 'ignore_element': ':)' }

# template
{% if not ignore_element %}
    {% include 'includes/element.html' %}
{% endif %}

This would work since its only shown for those that don't include this context value.

Any better solution options would depend on the logic behind why these 4 should be exempt from showing it

这篇关于如何使用Django中的if语句编写更好的模板逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆