【问题标题】:In Django's template system, how do I make it to do different things sometimes?在 Django 的模板系统中,我如何让它有时做不同的事情?
【发布时间】:2010-12-01 09:39:35
【问题描述】:
{% for p in posts %}
    <div style="width:50px;">
    blah
    </div>
{% endfor %}

但是,如果我希望 div 有 75% 的时间是 100px 怎么办? 25%的时间?随机。

【问题讨论】:

  • 你到底为什么要这样做?
  • 这是用于分割路径测试(或 AB 测试)吗?

标签: python html css django templates


【解决方案1】:

逻辑不会进入模板。

解决方案:编写一个新的模板标签,返回一个随机数,并将其用于宽度。

http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/

您的模板将如下所示:

{% for p in posts %}
    <div style="width:{% myrandomtag 0 100 %}px;">
    blah
    </div>
{% endfor %}

或其他。将您需要的逻辑放入标记的 python 代码中。

【讨论】:

    【解决方案2】:

    random filter 应该做的事情

    【讨论】:

      【解决方案3】:

      你可以使用Django的cycle方法:

      {% for o in some_list %}
      <tr class="{% cycle 'row1' 'row2' %}">
          ...
      </tr>
      {% endfor %}
      

      【讨论】:

      • 我的第一个答案是以 Jinja 的格式给出的,使用它的 cycler 功能,这在 Django 中不存在:/
      猜你喜欢
      • 2013-11-10
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多