Login

Using the {% widthratio %} template tag with CSS to create a bar graph

Author:
jcroft
Posted:
February 27, 2007
Language:
HTML/template
Version:
Not specified
Score:
19 (after 23 ratings)

The {% widthratio %} template tag is under appreciated! Here, it's combined with CSS to create a bar graphic for the results of an election (this example comes from this page, but has been modified slightly for simplicity's sake).

The widthratio tag can be used to create all sorts of graphs and charts, as well as things like tag clouds. Here, we pass it the number of votes for a candidate, the total number of votes in the election, and the integer 190, which is the width, in pixels, of a "full" bar on the bar graph. In other words, 100% = 190 pixels.

It works great!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<style type="text/css" media="screen">
  ul {
    margin: 0;
    padding: 0;
    width: 190px;
    background-color: #fff;
  }
  
  ul li {
    font-size: 11px;
    line-height: 20px;
    margin: 0;
    padding: 0;
    list-style-type: none;
    border-bottom: 1px solid #ebeff2;
    background-color: #fff;
  }
 
 ul li span {
    background-color: #a9d2f2;
    display: block;
    color: #125a95;
    font-weight: bold;
    padding: 0 0 0 5px;
    white-space: nowrap;
  }
</style>

<h3>Election results</h3>
<ul>
  {% for candidate in candidate_list|slice:":6" %}
    <li><span style="width: {% widthratio candidate.votes candidate.get_race.get_total_votes 190 %}px">{{ candidate.first_name }} {{ candidate.last_name }}</span></li>
  {% endfor %}
</ul>

More like this

  1. Bootstrap Accordian by Netplay4 5 years, 2 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 3 months ago
  5. Pagination Django with Boostrap by guilegarcia 8 years, 5 months ago

Comments

ericflo (on February 27, 2007):

This is awesome! It's a very creative way to use the widthratio tag.

#

grimboy (on March 6, 2007):

While this is quite clean anyone planning on using this should have the information in text as well so it can be read by someone using a screenreader.

#

eyeseast (on May 1, 2009):

Any tips on handling a mix of positive and negative numbers with this?

#

Please login first before commenting.