1

I am trying to display the results from a search that returns in dataframe format such as:

 data = {'title': ['Green Moon', 'Blue Dog', 'Orange Sun'],
         'url':  ['exampele.com/gm', 'example.com/bd', 'example.com/os'],
         'text': ['some string 1', 'some string 2', 'some string 3'}
 data = pd.DataFrame(data)

I want to display each title as a hyperlink to the url and then the context below it.

I had tried creating lists out of each column and using a for loop but that doesn't allow me to create a hyperlink:

urls = data.url.tolist()
texts = data.text.tolist()
titles = data.title.tolist()

example.html

 {% extends 'base.html' %}

 {% block content %}
    {% for title in titles %}
       {{ title }}
    {% endfor %}
    {% for text in texts %}
       {{ text }}
    {% endfor %}
 {% endblock %}

Expected Output with each title leading to the specified url:

 Green Moon
 some string 1

 Blue Dog
 some string 2

 Orange Sun
 some string 3
mjoy
  • 606
  • 2
  • 9
  • 19

2 Answers2

0

If you want the titles to be hyperlinks, it should be sufficient to wrap them in an tag. So something like:

in your app, add: app.jinja_env.globals.update(zip=zip) (this allows you to use zip in the template per this answer)

and then in the template:

{% for title, url in zip(titles, urls) %}
<a href={{url}}><h1>title</h1></a>
{% endfor %}
GLaw1300
  • 195
  • 9
0

I do not think you need pandas here. zip with unpacked values should help

Ex:

data = {'title': ['Green Moon', 'Blue Dog', 'Orange Sun'],
         'url':  ['exampele.com/gm', 'example.com/bd', 'example.com/os'],
         'text': ['some string 1', 'some string 2', 'some string 3']}

data = list(zip(*data.values()))

{% extends 'base.html' %}

{% block content %}
   {% for title, url, text in data %}
      <a href={{url}}>{{title}}</a>
      <p>{{text}}</p>
   {% endfor %}
{% endblock %}

Edit as per comment

data = {'title': ['Green Moon', 'Blue Dog', 'Orange Sun'],
         'url':  ['exampele.com/gm', 'example.com/bd', 'example.com/os'],
         'text': ['some string 1', 'some string 2', 'some string 3']}
data = pd.DataFrame(data)
data = data.apply(pd.Series.explode).to_dict(orient='records')

{% block content %}
   {% for item in data %}
      <a href={{item.url}}>{{item.title}}</a>
      <p>{{item.text}}</p>
   {% endfor %}
{% endblock %}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • I was just providing that as example data. The data I get comes in a dataframe and if I try to change it to a dictionary it converts my columns to keys and each row to a nested dictionary – mjoy Jul 21 '20 at 18:50
  • Oh ok..edited ans to use pandas to convert to a list of dicts – Rakesh Jul 21 '20 at 19:00