render_template怎么传参
时间: 2023-05-11 07:02:45 浏览: 362
在 Flask 中,可以使用 render_template 函数来渲染模板并传递参数。具体的方法是在 render_template 函数中传递参数,例如:
```
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
name = 'CSDN'
return render_template('index.html', name=name)
```
在这个例子中,我们将一个名为 name 的变量传递给了 index.html 模板。在模板中,可以使用 {{ name }} 来引用这个变量。
相关问题
render_template和render_template_string的区别
render_template和render_template_string都是Flask框架中的渲染模板的方法,区别在于:
render_template是从文件中加载模板,需要提供模板名称和模板所需的变量,例如:
```python
from flask import render_template
@app.route('/')
def index():
name = 'Alice'
return render_template('index.html', name=name)
```
render_template_string则是直接将模板字符串渲染成HTML,不需要提供模板文件名,例如:
```python
from flask import render_template_string
@app.route('/')
def index():
name = 'Alice'
template = '<html><body><h1>Hello {{ name }}!</h1></body></html>'
return render_template_string(template, name=name)
```
因此,如果需要从文件中加载模板,则使用render_template;如果需要直接将模板字符串渲染成HTML,则使用render_template_string。
render_template功能
`render_template`是Flask框架中的一个函数,用于渲染模板文件并返回渲染后的HTML内容。
具体来说,`render_template`函数的作用是将指定的HTML模板文件和模板变量传递给Jinja2模板引擎进行渲染,并将渲染后的HTML内容作为HTTP响应返回给客户端。在渲染HTML模板文件时,Jinja2模板引擎会根据模板变量的值动态生成HTML内容。
`render_template`的语法格式如下:
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
name = 'World'
return render_template('index.html', name=name)
```
在这个例子中,我们使用`render_template`函数渲染了一个名为`index.html`的模板文件,并将一个名为`name`的变量传递给模板。模板文件中可以使用`{{ name }}`这样的语法来引用这个变量。
需要注意的是,`render_template`函数默认会在`templates`目录下查找指定的模板文件。因此,我们需要将模板文件保存在`templates`目录下,才能让Flask框架正确地找到它们。
另外,`render_template`函数还支持传递多个变量和关键字参数,以及使用模板继承等高级特性,使得我们可以更加灵活地定制HTML页面。