BrettJ
BrettJ

Reputation: 1226

jinja2 - Display items without brackets/quotes

I'm returning a list to my Flask View but I want to display it without the brackets or single quotes.

My HTML is formatted simply around a bootstrap dropdown

<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Park Names
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
      {% for park in parks_found %}
      <a class="dropdown-item" href="#">{{ park }}</a>
      {% endfor %}
    </div>
  </div>

Which outputs the drop down as shown - I would love to display it without the brackets/quotes - Any help is much appreciated.

enter image description here

Upvotes: 2

Views: 5275

Answers (1)

gtalarico
gtalarico

Reputation: 4689

Looks like each park item is a list of one item and not a string. In other words, parks_found contains a list of lists and not a list of park names as strings.

Solution

You can either make sure parks_found is a list of strings before passing, or you can grab the first item from it. Alternatively, if it's possible that each item inside parks_found actually contains a list, you add another loop for each park item.

View

def view():
    return render_template('index.html',
                           parks_found=[['Park A'], ['Park B']],
                           flat_parks_found=['Park A', 'Park B'])

Html

<h1>Original</h1>
{% for park in parks_found %}
<p>{{ park }}</p>
{% endfor %}

<h1>Grab first item</h1>
{% for park in parks_found %}
<p>{{ park[0] }}</p>
{% endfor %}

<h1>Flattaned list</h1>
{% for park in flat_parks_found %}
<p>{{ park }}</p>
{% endfor %}

HTML Output


Original

['Park A']

['Park B']

Grab first item

Park A

Park B

Flattaned list

Park A

Park B


Upvotes: 2

Related Questions