Python Flask Basics Character Builder Items

Alternative to nested if inside of the for loop

At around 1:00 minute into this video, Kenneth said he couldn't think of another way to loop through the categories without including the colors.

Well, thanks to the Jinja templating documentation I found that you can use the following...

(I'm going to include as an answer so this question doesn't remain open the whole time).

3 Answers

Here's an alternative (and much cleaner) solution:

{% for category, choices in options.items() if category != 'colors' %}
...
{% endfor %}

This is of course because of Python's awesome syntax for control structures/loops!

Man I love Python!

Robin Malhotra
Robin Malhotra
14,883 Points

Could you explain how exactly this works? Shouldn't there be an && or something lying around there somewhere?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Robin Malhotra this doesn't need && or anything because Python allows you to apply a condition to the for loop.

Chris Grazioli
Chris Grazioli
31,220 Points

Dumb question about the block syntax:

{% %} whatever you like {% %}

Must you have something like endfor inside the {%%} or is this just convention?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You have to have the {% endfor %}

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Guess who doesn't write a lot of Jinja2? This guy. Thanks for pointing out a better solution.

Robin Malhotra
Robin Malhotra
14,883 Points

Another really really bad way to do this be to slice out the last row (i.e colors) in options. This of course, assumes you're using numpy.

But Iain Simmons' solution is awesome.