【问题标题】:Django strange template conditional renderingDjango 奇怪的模板条件渲染
【发布时间】:2015-07-15 04:36:32
【问题描述】:

这是我的 django 模板文件:

{% if chart %}
    {% block chart_content %}
       // some for loop
    {% endblock %}
{% else %}
    {% block content %}

    {% endblock %}
{% endif %}

这是我的“base.html”:

<div class = "container">
    {% block content %}
    {% endblock %}
</div>
{% block chart_content %}
{% endblock %}

当上述模板被渲染时,“if”和“else”内容都出现在页面中。所以换句话说,“if”和“else”都被评估了。谁能告诉我这是什么问题?

【问题讨论】:

    标签: python django


    【解决方案1】:

    来自Django template if statement always evaluates to true

    你不能像 if 一样将控制流标签包裹在一个块周围。您的问题是子模板对块数据的定义被使用只是因为它在那里。

    您可以通过将 if 标记放在块数据中来修复它。如果要在列表为空时继承父级的内容,请添加扩展为 {{ block.super }} 的 else 情况。

    【讨论】:

      【解决方案2】:

      关于模板规则的其他答案是正确的。但是,如果您只是想修正您的结果,也许这样的事情可以解决问题。

      {% block chart_content %}
          {% if chart %}
                 // some for loop
          {% endif %}
      {% endblock %}
      
      {% block content %}
      
      any conditionals you see fit on 
      the contents of this block
      for example:
      
      {% if not chart %}
         it did see like you wanted
         to have something here
         if chart was empty
      {% else %}
      
      {% endif %}
      
      
      {% endblock %}
      

      【讨论】:

        【解决方案3】:

        在“base.htm”模板中你确定并使用了块,默认情况下你会看到这些块的内容,在继承的模板上你只能覆盖在父模板中确定的块的内容,你不能设置出现或消失块,您可以通过重新确定没有内容的块来消除继承的块:

        {# base.html #}
        {% block x %}The X Block{% endblock %}
        

        并在继承中:

        {# index.html #}
        {% extends "base.html" %}
        {% block x %}{% endblock %}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-06-18
          • 2012-06-19
          • 2017-01-22
          • 1970-01-01
          • 2022-07-22
          • 2019-03-08
          • 1970-01-01
          • 2016-12-28
          相关资源
          最近更新 更多