0

I have a numpy chararray populated with items and I need for each item to be a clickable link in the html. But the href tag is displaying as text when I do this:

grid = np.chararray(shape=[2,2]).astype('|S55')

item = "<a href='#'>%s</a>" % str(item_number) 
grid[1,1] = item

I don't know that it matters, but I'm using pandas to create a dataframe and then sending it to the django template as html using the to_html() method.

df = pd.DataFrame(
    data=grid.astype(str),    # values
    index=side,    # 1st column as index
    columns=header   # 1st row as the column names
)
table = df.to_html()

How can I put a link inside a chararray such that it's clickable when rendered on the page?

wmfox3
  • 2,141
  • 4
  • 21
  • 28

1 Answers1

1

Use df.to_html(escape=False) to prevent the conversion of characters like <, > and & to HTML sequences (like &lt;, &gt; and &amp;):

import numpy as np
import pandas as pd

item_number = 99
grid = np.chararray(shape=[2,2]).astype('|S55')
item = "<a href='#'>%s</a>" % str(item_number) 
grid[1,1] = item

df = pd.DataFrame(grid.astype(str), columns=['a', 'b'])
print(df.to_html(escape=False))

yields

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>a</th>
      <th>b</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <th>1</th>
      <td></td>
      <td><a href='#'>99</a></td>
    </tr>
  </tbody>
</table>

enter image description here

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677