0

I want to keep my templates free of any logic - just html. I'm using a "for" loop in index.html to cycle through a list of posts. Here is the loop:

{% for recent in latest %}
<h1>{{ recent.title }}</h1>
<h2>{{ recent.category }}</h2>
{% endfor %}

What I want to do is in my Posts class, grab all the posts, checking that they match certain criterion, then place them in variables which could be sent to the template.

Here is the view (the logic of which I want to eventually move to models.py):

def index(request):

  # Get latest five posts

latest_posts = Post.objects.order_by('-published_date')[:5]

  # Get a single "top" category post.
top_post = Post.objects.get(category = 1)[:1]

  # set up some contexts

top = {'front_post': top_post}
context = {'latest': latest_posts}

return render(request, 'home/index.html', context, top)

Any suggestions?

1 Answer 1

2

You're taking the idea of keeping templates free of logic too far. There's a reason template languages provide things like for loops and boolean logic: without them you will wind up breaking the separation of concerns that an MVC framework is trying to enforce. Because what you will wind up with is embedding presentation information in your view logic and that's not what you want. As a simplistic example, consider adding the option of viewing your posts as a text file without adding a second view. If you keep the markup in the templates, it's easy. If you don't, it's not possible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.