在Flask中调用HTML文件中的python函数 [英] Calling python functions in HTML file in Flask

查看:176
本文介绍了在Flask中调用HTML文件中的python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的python文件中有一个文件夹列表,在一个HTML文件中,我遍历列表来显示我的页面上每个文件夹的名字。

  {%文件夹中的文件夹%} 
< li>< a href = {{文件夹}} > {{夹}}< / A>< /锂>
{%endfor%}

我想要做的就是当你点击该文件夹,它会做同样的事情,但在被点击的文件夹内。我有一个函数 open_folder ,它带有一个参数(点击的文件夹名称),但是我的问题是,我真的不知道如何调用带有参数的函数HTML文件。我见过的很多页面或教程只有python文件。在我的主文件中,我也有路由作为

  /< route> / 

我是Flask的新手,只是想知道是否有人有如何做到这一点的例子。这将不胜感激。

解决方案

假设文件夹想要作为自己的页面动态返回,适当的方法是使用独立的路径和视图来处理文件夹。类似如下:

$ p $ @ app.route(/ folder /< folder_name> /)
def文件夹(folder_name):
#做一些与文件夹名称
传递

您的HTML链接如下:

 < a href ={%url_for('folder',folder_name =文件夹)%}> {{文件夹}}< / a> 

很明显,您应该相应地更新路线,具体取决于文件夹,但这是链接到动态内容的烧瓶方式。


I have a list of folders in my python file, and in an HTML file I iterate over the list to display the names of each folder on my page.

{% for folder in folders %}
<li><a href = {{folder}}> {{folder}}</a></li>
{% endfor %}

What I am trying to do is make it so when you click on the folder, it will do the same thing, but inside the clicked folder. I have a function open_folder that takes one parameter (the clicked folder name), but my problem is that I don't really know how to call the function with a parameter in the HTML file. A lot of pages or tutorials I have seen only have the python files. In my main file I also have the route as

/<route>/

I am new to Flask and was just wondering if anybody had examples for how to do this. It would be much appreciated.

解决方案

With the assumption that folder is something whose contents you'd want to return dynamically as its own page, the appropriate way to do this would be to have a separate route and view that handles folders. Something like the following:

@app.route("/folder/<folder_name>/")
def folder(folder_name):
    # do something with folder_name
    pass

And in your HTML you would link to it as follows:

<a href="{% url_for('folder', folder_name=folder) %}">{{ folder }}</a>

Obviously you'd want to update the route accordingly, depending on the contents of folder, but that's the "Flask way" of linking to dynamic content.

这篇关于在Flask中调用HTML文件中的python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆