Best method for dynamically building URL with Flask url_for

Question:

I have to create an URL in JavaScript with url_for because I should use whole table row as a link which i cannot do it in HTML. Sample below:

{% for x in last_orders %}
<tr id="x">
    <td>something here</td>
    <td>something here</td>
</tr>
{% endfor %}

And Flask:

@app.route("/some/page/<int:id>/", methods=['POST', 'GET'])
def xxx_page(id):

I can make table row like a link by using Jquery function .click() but with this method I cannot use url_for in proper way.

I saw in another topic that I can send variables with Post but I dont want to change my URL system because this is more user friendly.

Maybe I can create dummy URL with url_for (/some/page/0) and then change that string with JavaScript but I am not sure this method is the best.

Edit: My method is like this:

$(".row").click(function() {
    var id = $(this).attr("id");
    var where = `{{ url_for('xxx_page', id=0) }}`;
    where = where.slice(0,-2).concat(id + "/");
    window.location = where;
  });
Asked By: maydin

||

Answers:

If the elements of last_orders contain the prefix used in the xxx_page function(s), then you can just make an a tag within the td.

<td><a href={{ url_for('{}_page'.format(x)) }}>something here</a></td>

EDIT: After rereading your question, you’re looking to make the entire cell clickable. There are a couple options in JavaScript. You can listen to clicks on all the td elements, and then trigger a click on their child a.

# Don't actually use an anonymous function. Define it elsewhere.
$('body').off('click.order')
    .on('click.order', 'td', function(e) {
        $(this).find('a').trigger('click');
    });

OR (and I like this option much less than the first one) you could set a data element on the td elements with the address.

<td data-url='{{ url_for('{}_page'.format(x)) }}'>something here</td>

Then in your click listener, do this.

window.location.href = $(this).attr('data-url');
Answered By: Allie Fitter
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.