0

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?

  • You can't increment variables in the Django template language. The [duplicate question](https://stackoverflow.com/questions/1107737/numeric-for-loop-in-django-templates) 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. – Alasdair Jan 26 '18 at 14:51
  • @Alasdair Thanks. It worked and simple. There are lot of things to learn :). – Chandimal Harischandra Jan 26 '18 at 14:59

1 Answers1

-2

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

ptr
  • 3,292
  • 2
  • 24
  • 48