开发者

How to break "for loop" in Django template

I have this code

    {% for account in object_list %}
        <tr>
        {% for field, value in book.get_fields %}
              <th>{{ field.ve开发者_运维问答rbose_name }}</th> 
        {% endfor %}
        </tr>
    {{ break }}
    {% endfor %}

I want to break the for loop after first iteration. break is not working


I think you should use slice to achieve your goal

{% for account in object_list|slice:":1" %}


There is no break in Django template system. Django template system is not programmed with python but with its own language.

Depending on what you need to do, you might find this question useful. Otherwise, just put the one and only account you are trying to print on HTML on a special field on your RequestContext.


You can't use break statement but you can choose not to print them on html. It's not a best solution but you can use it. I use the following one;

{%for tumbnail in image %}
         {%if tumbnail.object_id == element.id %}
          <img src="/media/{{ tumbnail.image }}" class="tr_all_hover"alt="">

{{ "<!--" }}
  {%endif%} 
{%endfor%}     
{{ "-->" }}

Its basicly seem like this on browser. http://i.stack.imgur.com/MPbR3.jpg


     {% for i in list %}
      {% if forloop.counter < 11 %}                                     
        <tr>
          <td>{{ forloop.counter }}</td>
          <td>{{ i.product__name }}</td>
          <td>{{ i.brand__name }}</td>
          <td>{{ i.country__name}}</td> 
          <td>{{ i.city__name}}</td>  
                     
        </tr>
      {% endif %} 
             
      {% endfor %}


You can use your Django template system for loop in javascript for loop as inner loop and can use break as follows :-

for(var i=0;i<1;i++){
        {% for owner in Owner %}
            id  = "{{owner.id}}";
            if(id == pk1){
                f="{{owner.flat}}";
                break;
            }             
        {% endfor %}
     }


I found a way to do this with a condition. It's ugly and hacky, but it works (for me). first is what the OP wanted, but this answers the actual question more closely.

Given this:

obj = {
  'children': [
    { 'possessions' : { 'toys': [] } },
    { 'possessions' : { 'toys': ['train'] } }
    { 'possessions' : { 'toys': ['train', 'ball'] } }
  ]
}

I wanted to know if my obj has any children with possessions that are toys.

Here's what I did:

Python Equivalent:

if ([child for child in obj.children if child.possessions.toys]):
  # Whatever

Django Template:

My approach was to use regroup to build sets of candidates which did or didn't match the criteria:

{% regroup obj.children by possessions.toys|length_is:"0" as by_toys %}
{% for check in by_toys %}{% if check.grouper == False %}
  Whatever
{% endif %}{% endfor %}

regroup builds a new object that is essentially:

[
  { 'grouper': '', 'list': [/*...*/] },
  { 'grouper': True, 'list': [/*...*/] },
  { 'grouper': False, 'list': [/*...*/] }
]

The length_is:"0" makes sure that we have at most three elements in that list and the grouper is either True or False or ''. Then we iterate over the list and check for a False value.

  • If there are no children it'd be an empty list and the if would never be hit.
  • If no children have toys, it'd be a list without a False grouper.
  • If all children have toys, it'd be a list with a False grouper.
  • If some children have toys, it'd be a list with False and True groupers.


In this case you can check if forloop.counter == 1 or if forloop.first and simply print that first item.

  {% for account in object_list %}
      {% if forloop.first %}
        <tr>
        {% for field, value in book.get_fields %}
              <th>{{ field.verbose_name }}</th> 
        {% endfor %}
        </tr>
      {% endif %}
    {% endfor %}


There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.)

1- Use with to define a variable to determine current status,

2- Use a template custom tag to change statement to negate current status.

in template use like this:

{% with statement=1 %}
   {% for obj in listObject %}
       {% if ifStatement and statement %}
           {% changeStatement statement as statement %} // when u don't want to enter in if again.
           Do your job here!!
       {% endif %}
   {% endfor %}
{% endwith %}

In template custom tags :

@register.simple_tag
def changeStatement(status):
    return not status


Slicing is the best as mentioned on top!

Alternatively, you can use a template variable for more complex continue/breaks:

How can I use break and continue in Django templates?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜