Question

I'm using Flask and want to render html pages and directly focus on a particular dom element using /#:id.

Below is the code for default / rendering

@app.route('/')
def my_form():
    return render_template("my-form.html")

Below is the function being called upon POST request.

@app.route('/', methods=['POST'])
def my_form_post():
    #...code goes here
    return render_template("my-form.html")

I want to render my my-form.html page as my-form.html/#output so that it should directly focus upon the desired element in the dom.

But trying return render_template("my-form.html/#output") tells that there's no such file and trying @app.route('/#output', methods=['POST']) doesn't work either.

UPDATE:

Consider this web-app JSON2HTML - http://json2html.herokuapp.com/

What is happening: Whenever a person clicks send button the textarea input and the styling setting is send over to my python backend flask-app as below.

@app.route('/', methods=['POST'])
    def my_form_post():
        #...code for converting json 2 html goes here
        return render_template("my-form.html",data = processed_data)

What I want: Whenever the send button is clicked and the form data is POSTED and processed and the same page is redirected with a new parameter which contains the processed_data to be displayed. My problem is to render the same page appending the fragment identifier #outputTable so that after the conversion the page directly focuses on the desired output the user wants.

Was it helpful?

Solution

The fragment identifier part of the URL is never sent to the server, so Flask does not have that. This is supposed to be handled in the browser. Within Javascript you can access this element as window.location.hash.

If you need to do your highlighting on the server then you need to look for an alternative way of indicating what to highlight that the server receives so that it can give it to the template. For example:

# focus element in the query string
# http://example.com/route?id=123
@app.route('/route')
def route():
    id = request.args.get('id')
    # id will be the given id or None if not available
    return render_template('my-form.html', id = id)

And here is another way:

# focus element in the URL
#http://example.com/route/123
@app.route('/route')
@app.route('/route/<id>')
def route(id = None):
    # id is sent as an argument
    return render_template('my-form.html', id = id)

Response to the Edit: as I said above, the fragment identifier is handled by the web browser, Flask never sees it. To begin, you have to add <a name="outputTable">Output</a> to your template in the part you want to jump to. You then have two options: The hacky one is to write the action attribute of your form including the hashtag. The better choice is to add an onload Javascript event handler that jumps after the page has loaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top