简体   繁体   中英

django template - for loop date display with slice

I have a django 1.4.6 project. I am trying to display my blog entries in my template that are not dated in the future, so I cobbled this code in my models.py page, which works:

    #if the blog is post/future dated, do not display the blog entry.
    @property
    def is_past_date_published_blog(self):
        if self.blog_post_date_published < date.today():
            return True
        return False

Now I am wanting to just display the 1st 3 blog entries (I have more than 10 blog entries), so I used a slice:3 as shown below:

            {% for blog_post in blog_posts|slice:":3" %}
                {% if blog_post.is_past_date_published_blog %}
                    .......
                    .......
                 {% endif %}
            {% endfor %}

However, this will only display two entries, as the loop does count the blog entry that is not included by the inner if condition. I have tried to place the for loop inside the if statement, but this does not work. I am now stumped.

How would I write this code to display three blog entries that are before today's date?

Don't put too much logic in the template :

The goal is not to invent a programming language. The goal is to offer just enough programming-esque functionality, such as branching and looping, that is essential for making presentation-related decisions.

And the task you've described is not presentation related at all.

Filter out blog entries that are not dated in the future in the view and pass it to the template. Eg:

blog_posts = BlogPost.objects.filter(blog_post_date_published__lt=datetime.today())[:3]

Then, in the template, just loop through these blog posts you've filtered before:

{% for blog_post in blog_posts %}
    # display a blog post
{% endfor %}

Hope that helps.

You could pass from your view, only the blog posts that are published before today and then use |slice:":3" as you are doing now to display only three. It is easier to manipulate the data in the view than in the template

An alternative would be to have a counter variable in the template which is incremented inside the inner if condition, but it is discouraged to do any data altering in the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM