So I am using python flask along with some HTML and CSS to create a dynamic website to display reviews about universities. However I am facing a slight issue in that I have flask gives HTML reviews and reviews contain attributes such as username, date, the review comments, and overall rating (out of 5). However for the overall rating I want to display them on the website as starts, so I have 5 stars and have 2 different icons for the starts 1 that is filled and 1 that is hollow, so e.g if a review was rated 3/5 I have 3 filled stars and 2 hollow stars. Currently, I have to "hard code" e.g rating through if statements and it looks messy and doesn't really work well if I have to add other ratings.
HTML code
<section id="reviews">
<div >
<!-- Get all the data from postgres database-->
{% for review in reviews.items %}
<div >
<div >
<div >
<div >
<img src="{{ url_for('static', filename='images/Lincoln-Logo.png') }}" width="50" height="50" alt="profile">
</div>
<div >
<strong>{{ review.user_name }}</strong>
<span> {{ review.date.strftime('%Y-%m-%d') }}</span>
</div>
</div>
<!--Hard coded the overall rating star display (How can I do this better?)-->
<div >
{% if review.overall_rating == 1 %}
<i ></i>
<i ></i>
<i ></i>
<i ></i>
<i ></i> <!-- Holo star -->
{% endif %}
{% if review.overall_rating == 2 %}
<i ></i>
<i ></i>
<i ></i>
<i ></i>
<i ></i>
{% endif %}
{% if review.overall_rating == 3 %}
<i ></i>
<i ></i>
<i ></i>
<i ></i>
<i ></i>
{% endif %}
{% if review.overall_rating == 4 %}
<i ></i>
<i ></i>
<i ></i>
<i ></i>
<i ></i>
{% endif %}
{% if review.overall_rating == 5 %}
<i ></i>
<i ></i>
<i ></i>
<i ></i>
<i ></i>
{% endif %}
</div>
</div>
<div >
<p>{{ review.comments}}</p>
</div>
</div>
{% endfor %}
</div>
</section>
So I am wondering If there is a way to get rid of the if statements for each value from 1 - 5 and do it in a less hardcoded fashion, so it makes it easier when adding other ratings.
CodePudding user response:
you can make two loops in total without if loops, first for loop to print the full stars X times (where X is the rating), and 2nd the half star loop for 5 - X times.
in my example the overall_rating
is the variable with value 0 to 5:
jinja template:
<pre>
{% for ii in range(1, overall_rating 1) %}
<i ></i>
{% endfor %}
{% for ii in range(1, 5 - overall_rating 1) %}
<i ></i> <!-- Holo star -->
{% endfor %}
Edited to adjust the template more to your case
CodePudding user response:
you can use loop to loop over review.overal_rating to render html tag.