使用 flask 渲染 HTML 页面 /#:ID

render html page /#:id using flask

本文关键字:ID 页面 flask 渲染 HTML 使用      更新时间:2023-09-26

我正在使用Flask,并希望使用 /#:id 渲染 html 页面并直接关注特定dom element

下面是默认/渲染的代码

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

下面是根据请求调用POST函数。

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

我想将我的my-form.html页面呈现为my-form.html/#output,以便它应该直接关注 dom 中所需的element

但是尝试return render_template("my-form.html/#output")告诉没有这样的文件,尝试@app.route('/#output', methods=['POST'])也不起作用。

更新:

考虑此 Web 应用程序JSON2HTML - http://json2html.herokuapp.com/

发生了什么:每当有人单击send按钮时,文本区域输入和样式设置都会发送到我的python后端烧瓶应用程序,如下所示。

@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)

我想要的:每当单击send按钮并POSTED和处理表单数据时,都会使用包含要显示processed_data的新参数重定向同一页面。我的问题是呈现附加片段标识符#outputTable的同一页面,以便在转换后页面直接关注用户想要的所需输出。

URL 的片段标识符部分永远不会发送到服务器,因此 Flask 没有。这应该在浏览器中处理。在 Javascript 中,您可以window.location.hash访问此元素。

如果您需要在服务器上进行突出显示,则需要寻找另一种方法来指示服务器接收的突出显示内容,以便它可以将其提供给模板。例如:

# 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)

这是另一种方式:

# 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)

对编辑的回应:正如我上面所说,片段标识符由网络浏览器处理,Flask 永远不会看到它。首先,您必须在要跳转到的部分将<a name="outputTable">Output</a>添加到模板中。然后,您有两种选择:笨拙的选择是编写表单的action属性,包括主题标签。更好的选择是添加一个onload Javascript 事件处理程序,该处理程序在页面加载后跳转。