【问题标题】:Is there a way to go to a specific part of html page with flask? [duplicate]有没有办法用烧瓶转到 html 页面的特定部分? [复制]
【发布时间】:2020-12-15 22:55:56
【问题描述】:

我正在创建一个网页,我想使用 Flask 的 render_template 转到该页面的特定部分(在本例中称为结果)。

有没有办法做到这一点,例如通过将参数 go_to_results = True 传递给 render_template:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':

        if 'file' not in request.files:
            return render_template('index.html')

        file = request.files['file']

        if file.filename == '':
            return render_template('index.html')

        prediction = predict(file, 3, percentage=True)

        return render_template('index.html', prediction_html = prediction, go_to_results = True)
        
    return render_template('index.html')

我找到了这个示例,但它不符合我的需要,因为我只使用了 1 个 HTML 页面('index.html')。 Link to a specific location in a Flask template.

更新工作解决方案: 我将此添加到 HTML 结果部分:

<a href="#results">
</a>

然后我使用了这个 JS 代码。

<script>
    function jumpToHash(hash){
        if (hash){
            var url = location.href;
            location.href = "#results";
        }
    }
jumpToHash({{ anchor }});
</script>

【问题讨论】:

    标签: python html flask jinja2


    【解决方案1】:

    您可以在模板中添加一点点 JS 并传递锚点。

    在你的烧瓶中:

    render_template('index.html', anchor="your_tag_id")
    

    要添加到index.html的JS代码:

    <script>
        function jump(h){
            var url = location.href;               //Save down the URL without hash.
            location.href = "#"+h;                 //Go to the target element.
            history.replaceState(null,null,url);   //Don't like hashes. Changing it back.
        }
    
        jump({{ anchor }});
    </script>
    

    感谢 JS here

    【讨论】:

    • 谢谢卢卡,你的解释很清楚,虽然它似乎不起作用。不幸的是,我对 JS 的了解为 0。我是否需要更改 JS 函数跳转中的某些内容?或者可能是由于 html 文件中的其他 JS 代码(太大无法粘贴此处):
    • 不得不说.... 作为预防措施,将 js 移动到 HTML 的底部
    • 我试过这样做,不幸的是没有工作。我还注释掉了所有其他的 JS 代码,但它仍然不起作用。我还硬编码了“结果”而不是 {{ anchor }},这也不起作用......
    • 你确定你的结果 div 有 id="results" 吗?您能否尝试这里提出的其他解决方案:stackoverflow.com/questions/13735912/…
    • 我确定,不过谢谢。我还尝试了其他解决方案,并尝试重置 Flask 应用程序等。我现在将在其他地方获得一些调试帮助,让您知道结果。
    猜你喜欢
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2017-06-22
    • 2019-09-21
    • 2022-09-24
    • 2020-11-09
    相关资源
    最近更新 更多