user3650429 user3650429 - 2 years ago 107
HTML Question

Django cycle template won't allow for a new line if I do my html looks scrambled How can I fix this?

I am trying to grasp the usage of Django's cycle template tag. My layout in my html is 3 post from right to left and 5 posts from top to bottom. I used the cycle tag so that right after the sixth post a horizontal bar goes under the whole width of my row. I want to put ads there. So it looks like this


I kind of figured it out after playing around with the code for a while. My dilemma now is I want to put the code for my ad where the bar is. but the code is to long and if I go to a new line, even if I use this \ it still scrambles my html. The way I have it now is like this

{% block content %}

<div class="row" id="scheme">
{% for post in posts %}
<div class="col-xs-12 col-md-4" id="split">
<div class="thumbnail thumb">
<h6 id="date">{{ post.publish|date }}</h6>

{% if post.image %}
<img src="{{post.image.url}}" class="img-responsive post">
{% elif post.image_url %}
<img src="{{post.image_url}}" class="img-responsive post">
{% else %}
<p>upload an image</p>
{% endif %}

<div style="border-bottom: thin solid lightslategray; padding-bottom: 15px;"></div>

<div class="caption" id="cap">
<a href="{{ post.get_absolute_url }}">
<h5 class="post-title" id="title">{{post.title}}</h5>

{% if user.is_authenticated %}
<a href="{% url 'blog:delete' %}" class="btn" role="button">delete</a>
<a href="{% url 'blog:update' post.slug %}" class="btn" role="button">edit</a>
{% endif %}
{% cycle "" "" "" "" "" "<div id='adspace' class='col-xs-12 col-lg-12' style='height:200px; background-color: #5b80b2; margin-bottom: 60px'></div>" "" "" "" "" "" "" "" "" "<div class='col-sm-12'></div></div><div class='row'>" %}
{% endfor %}

{% include "pagination.html" with page=posts %}

{% endblock content%}

The cycle template is way to long. I'm hoping there is a more sophisticated way of doing this. What is a better way to use the cycle tag or rather a shorter way? I'm open to any suggestions. Thanks all.

Answer Source

To insert something special after the sixth item in the loop, just use the forloop counter (docs):

{% for post in posts %}

    ... Post content here

    {% if forloop.counter == 6 %}
        <div id='adspace' class='col-xs-12 col-lg-12' style='height:200px; 
        background-color: #5b80b2; margin-bottom: 60px'></div>
    {% endif %}

{% endfor %}

Similarly you can add other content at other specific counter points in your loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download