0

I am new to programming and struggling with an exercise using Jinja2 templates with Python 2.7 in Google App Engine. I am supposed to request user input, generate a random number based on that input, store both values in a pair of lists (or a dictionary or tuple), then use Jinja2 template to store ALL input variables and the random number that was generated by them in a two column table. I am successfully storing and displaying one row, but the table is not storing multiples.

Python file

class MainHandler(webapp2.RequestHandler):
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('index.html')
        template_values = {
            'title': 'Enter a number'
        }
        self.response.write(template.render(template_values))

class ListHandler(webapp2.RequestHandler):
    def post(self):
        myList = []
        listTwo = []
        n = int(self.request.get('num'))
        r = int(random.random()*n) + 1
        myList.append(r)
        listTwo.append(n)
        template = JINJA_ENVIRONMENT.get_template('list.html')
        template_values = {
            'title': 'random number',
            'list': myList,
            'listTwo': listTwo
        }
        self.response.write(template.render(template_values))

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/list', ListHandler),
    ], debug=True)

HTML file

<table>
  <tr><th>Random Numbers</th><th>Chosen Numbers</th></tr>
  <tr>
    {% for i in list %}
      {% if i % 2 == 0 %}
        <td class='even'>{{i}}</td>
      {% else %}
        <td class='odd'>{{i}}</td>
      {% endif %}
    {% endfor %}

    {% for i in listTwo %}
      <td>{{i}}</td>
    {% endfor %}
  </tr>
</table>

I've tried searching through forums and Python/Jinja documentation, but so far my debugging has been unsuccessful. Please help!

coralvanda
  • 6,431
  • 2
  • 15
  • 25
schne489
  • 79
  • 1
  • 6

1 Answers1

0

You're checking if your value i is even/odd but it looks like you want to alternate depending on position in list.

There's an example in the jinja2 docs that's exactly what you're trying to do.

{% for row in rows %}
    <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}

Also, many UI libraries e.g. Bootstrap (http://getbootstrap.com/css/) have a .table-striped class that does this for you.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Jeremy Gordon
  • 551
  • 4
  • 15