我想将app.py中的文件名解析为graph.js。但我无法获取js文件的变量名称。我正在使用烧瓶
这是文件结构
- app/
- flask_app.py
- templates/
-> index.html
-> data/
-> file1.csv
- static/
-> js/
-> create-graph.js
我的应用看起来像这样(相关部分):
data_files = ["file1.xlsx", "file2.xlsx", "file3.xlsx"]
cur = 0
df1 = pd.read_excel("data/" + data_files[cur])
df1.to_csv('templates/data/' + data_files[cur][:10] + '.csv', encoding='utf-8', index=False)
所以我有从xlsx转换为csv的文件,然后我想用它的名字拉出csv文件。我需要将data_files
和cur
传递给我的.js文件... 以下是相关的.js:
function parseData(createGraph) {
var name = '{{data_files[cur][:10]}}';
console.log(name);
Papa.parse("static/data/" + name + ".csv", {
download: true,
complete: function(results) {
createGraph(results.data);
}
});
}
但似乎我无法将文件名传递到此处:var name = '{{data_files[cur][:10]}}';
在控制台上,它为我提供完全相同的字符串
那么我做错了什么?
我也尝试将其添加到app:
@app.route('/create-graph.js')
def script():
return render_template('create-graph.js', fileName="data_files[cur][:10]")
仍然没有运气......
如果有人问,这里我如何调用.js文件:
...
<script src="{{ url_for('static', filename='js/create-graph.js') }}"></script>
...
答案 0 :(得分:0)
You need to pass the parameter to render_template as a variable with desired values.
If you've only one file then you can just use.
@app.route('/create-graph.js')
def script():
data_file = "test.csv"
return render_template('create-graph.js', file_name=data_file)
function parseData(createGraph) {
var name = '{{file_name}}';
console.log(name);
Papa.parse("static/data/" + name + ".csv", {
download: true,
complete: function(results) {
createGraph(results.data);
}
});
}
If data_files is a list of list or dictionary of the list.
function parseData(createGraph) {
var name = '{{data_files_cur[:10]}}'; // here you can get at max 10 files
console.log(name);
Papa.parse("static/data/" + name + ".csv", {
download: true,
complete: function(results) {
createGraph(results.data);
}
});
}
@app.route('/create-graph.js')
def script():
# define cur and data_files
data_files_cur = data_files[cur];
return render_template('create-graph.js', data_files_cur=data_files_cur)
It looks you don't know much about flask template engine syntax. I would recommend you should read about Jinja/Mako or Django template syntax.