如何在flask.render_template渲染html页面时动态执行页面中的JavaScript函数
时间: 2024-10-13 19:12:22 浏览: 45
在Flask框架中,当你需要在HTML模板中动态执行JavaScript函数时,可以结合 Jinja2 模板引擎和Python表达式。首先,在你的Python视图函数中获取到需要的数据,并将其传递给模板。然后,在HTML模板中,你可以这样操作:
```python
from flask import render_template
def your_view_function():
data = {
'javascript_data': 'some_value', # 这里是你想要传入的JavaScript变量
'javascript_function': 'yourFunctionName' # JavaScript函数名
}
return render_template('your_template.html', **data)
```
接着,在`your_template.html`文件中,你可以这样引用并调用这个函数:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function {{ javascript_function }}() { <!-- 使用{{ }}包裹Python表达式 -->
// 这里是你的JavaScript代码,会使用到javascript_data
console.log({{ javascript_data }});
}
</script>
</head>
<body>
<button onclick="{{ javascript_function }}">点击执行JavaScript函数</button>
</body>
</html>
```
在这个例子中,当用户点击按钮时,`yourFunctionName`会被替换为Python字典`data`中的`javascript_function`值,从而动态地执行相应的JavaScript函数。
阅读全文
相关推荐


















