You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask使用render_template传参至模板时出现语法错误求助

问题解决:Flask模板传参语法错误

错误原因

代码中return(render_template('home.html'), name='name')存在语法错误——你把模板变量参数放到了return的元组里,而非作为render_template函数的参数传递。Python不允许在元组后直接追加关键字参数,因此触发了SyntaxError。

修正后的Flask代码

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    # 将name参数作为render_template的参数传入
    return render_template('home.html', name='name')

模板代码(无需修改)

<h1> This is Home Page </h1>
<h2>{{ name }}</h2>

说明

render_template函数的第二个及后续参数就是要传递给模板的变量,格式为变量名=值,这样模板中的{{ name }}就能正确读取到传递的'name'值。

内容的提问来源于stack exchange,提问作者user23092723

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:24:53