简体   繁体   中英

Django- Template Tag Approach

I'm trying to figure out a way to print out a heading of a category if the specific category exists. The issue I have is since Im running through my articles via for loops, I cant just post the heading if the category exists, otherwise it will print out that heading multiple times. For example this:

{% for x in todays_articles %}
 {% with x.categories.all as categories %}
 {% for category in categories %}
  {% if category.title == "nfl" %}
  <p><H1>NFL:
   <p>{{x.title}} {{category}}
  {% endif %}
  {% if category.title == "nba" %}
   <p>{{x.title}} {{category}}
  {% endif %}
 {% endfor %}
{% endwith %}

will print out NFL/NBA multiple times. I could just copy and paste it multiple times.

<P>NFL: 

{% for x in todays_articles %}
 {% with x.categories.all as categories %}
 {% for category in categories %}
  {% if category.title == "nfl" %}
  <p>{{x.title}} {{category}}

and do that for every category. Im just wondering if there is a smarter approach to this. Thanks.

我不是100%知道您在这里做什么,但是我认为您需要{% ifchanged %}模板标记。

You could consider using table tag and then print result of NFL and NBA in two different columns. I can elaborate further if you need!

If I'm understanding correctly, you seem to have a section of code you need to repeat multiple times in your template.

For that you can use a template include .

However if your items are sorted by category already, you may want to simply use the ifchanged tag as Daniel Roseman pointed out. If your items are not sorted by category, you may want to split these items in your view code or via separate database queries and inject them as separate variables into your 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