1

I need to render block of html code 5 times in template file. Like in php I tried something like below,

{% extends 'stories/base.html' %}
{% block body %}
<h1>This is rating page</h1>

<section class='rating-widget'>
  {% with count = 0 %}
  {% while count < 5: %}
      <div class='rating-stars text-center'>
          <ul class='stars'>
              <li class='star selected' title='Poor' data-value='1'>
                  <i class='fa fa-star fa-fw'></i>
              </li>
              <li class='star selected' title='Fair' data-value='2'>
                  <i class='fa fa-star fa-fw'></i>
              </li>
              <li class='star selected' title='Good' data-value='3'>
                  <i class='fa fa-star fa-fw'></i>
              </li>
              <li class='star selected' title='Excellent' data-value='4'>
                  <i class='fa fa-star fa-fw'></i>
              </li>
              <li class='star selected' title='WOW!!!' data-value='5'>
                  <i class='fa fa-star fa-fw'></i>
              </li>
          </ul>
      </div>
        {% count += 1 %}
      {% endwhile %}
  {% endwith %}
</section> 

But I couldn't get expected result. It gives me syntax error "'with' expected at least one variable assignment". Is this possible or what is the proper way to implement this kind of loop in django?

2
  • You can't increment variables in the Django template language. The duplicate question I linked to has several suggestions. For looping 5 times, {% for i in 'xxxxx' %} is simplest. For larger numbers, I like the suggestion of the times filter. Commented Jan 26, 2018 at 14:51
  • @Alasdair Thanks. It worked and simple. There are lot of things to learn :). Commented Jan 26, 2018 at 14:59

1 Answer 1

-2

You need to remove the spaces between the count = 0 part, due to the way the {% with %} template tag parses variable assignment.

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

2 Comments

That would fix the issue with the with tag, then you'll immediately get an error on the next line {% while count < 5: %}. The key point is that you can't do this kind of thing in the Django template language.
@ptr Thanks for your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.