Home > Net >  Python Flask - Turn table column value into hyperlink of URL in another?
Python Flask - Turn table column value into hyperlink of URL in another?

Time:07-12

I have a sample dataframe in views.py:

df = pd.DataFrame({'name':('Nick', 'Nick', 'Nick', 'David'), 
                   'link':("www.google.com", "www.aol.com", "www.yahoo.com", "www.google.com")})

enter image description here

I send this dataframe back to my home.html in the render_template line:

return render_template("home.html", column_names=df.columns.values,
                                           row_data=list(df.values.tolist()),
                                           zip=zip)

Which is then showed in my home.html through:

div style="position:relative; z-index: 1; top:-125px;">
        <table id="table_id"  style="width:100%">
            <thead>
            <tr>
                {% for col in column_names %}
                    <th>{{ col }}</th>
                {% endfor %}
            </tr>
            </thead>
            <tbody>
            {% for row in row_data %}
                <tr>
                    {% for col, row_ in zip(column_names, row) %}
                        <td>{{ row_ }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>

I want the name column to have a hyperlink to the URL in the link column, and then I want to remove the link column.

Example: If the user was to click David in the table, it would open a new tab to www.google.com.

I have only seen examples where people turn the URL into a clickable link, rather than use it on another column.

Any suggestions?

CodePudding user response:

If you want each column header to be a link to search google for that col header's value:

<tr>
    {% for col in column_names %}
        <th><a href="https://www.google.com/search?q={{ col }}" target="_blank">{{ col }}</a></th>
    {% endfor %}
</tr>
  • Related