I have a websockets app where I show the clients connected. I use flask for the front-end.
When a new client is connected I add it to the clients
list in python.
HTML side, I have a table who receives the clients list through Jinja, and it creates a row for every client connected. This table is refreshed every 2 seconds with js.
My clients list is a list of dictionaries:
clients = [
{ 'cp_id':'Jhon',
'last_heartbeat_from_now':datetime.utcnow()
}
...
]
I have my table like this:
<table id="clients">
<tr>
<th>Name</th>
<th>Last time connected </th>
<th>Health</th>
</tr>
{% for i in clients %}
<tr>
<td>{{ i['cp_id'] }}</td>
<td>{{ i['last_heartbeat_from_now'] }}</td>
<td><img src="{{ url_for('static', filename='green.png') }}" ></td>
</tr>
{% endfor %}
</table>
I want to make every row <tr>
to be clickable and to redirect to a dynamic URL with the name of the person. For example when I click Jhon in the HTML I want to create the dynamic url : localhost:5000/dashboard/Jhon.
I tried using
<tr onclick="{{ url_for('dashboard', cp_id = i['cp_id']) }}">
But it doesn't do anything. I tried making a data-href:
<tr data-href="{{ url_for('dashboard', cp_id = i['cp_id']) }}">
But I'm not sure how to use this.
And finally my python code for the route part is this:
@app.route('/dashboard/<string:cp_id>', methods=["GET", "POST"])
def dashboard(cp_id):
return render_template('dashboard.html')
CodePudding user response:
You were almost there!
The best way to do this is using data-href
:
<tr data-href="{{ url_for('dashboard', cp_id = i['cp_id']) }}">
Your rows are added dynamically so your script needs to delegate events. This means that the onclick event need to come from a static parent (if you can, the closest one from the dynamic children, in this case I use document).
If you don't delegate events from the static parent to the dynamic child, it won't work. Like this for example:
jQuery("tr[data-href]").on("click", function () ...
This won't work in you html.
Delegating event handlers will make the job.
And you add your jQuery script:
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery(document).on("click", "tr[data-href]", function() {
window.location.href = jQuery(this).attr('data-href');
});
});
</script>
And if you want to add the 'hand' effect on hovering the row, just add this to your CSS:
[data-href] { cursor: pointer }