Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python url_for()中的Jinja变量_Python_Sql_Sqlite_Flask_Jinja2 - Fatal编程技术网

Python url_for()中的Jinja变量

Python url_for()中的Jinja变量,python,sql,sqlite,flask,jinja2,Python,Sql,Sqlite,Flask,Jinja2,我有一个通过链接访问的服务列表,我使用Jinja中的for语句和flask提供的url_for函数来显示它们 {%用于服务中的服务%} {%endfor%} 正如@arsho在routes文件中声明的服务列表中所回答的那样,这可以很好地工作 app.py: 服务=[ { 服务url:第一页, 服务名称:首页服务 }, { 服务url:第二个页面, 服务名称:第二页服务 }, { 服务url:第三个页面, 服务名称:第三页服务 } ] 在本例中,我使用以下语句恢复存储在SQLite数据库中的列表

我有一个通过链接访问的服务列表,我使用Jinja中的for语句和flask提供的url_for函数来显示它们

{%用于服务中的服务%} {%endfor%} 正如@arsho在routes文件中声明的服务列表中所回答的那样,这可以很好地工作

app.py:

服务=[ { 服务url:第一页, 服务名称:首页服务 }, { 服务url:第二个页面, 服务名称:第二页服务 }, { 服务url:第三个页面, 服务名称:第三页服务 } ] 在本例中,我使用以下语句恢复存储在SQLite数据库中的列表 services=services.query.all

服务类声明如下:

models.py

类服务DB.Model: id=db.Columndb.Integer,主键=True 服务名称=db.Columndb.String32 服务url=db.Columndb.String32 使用烧瓶外壳,我可以查看数据库中的内容:

>>>service = Services.query.all()
>>>for service in services:
...   service.service_name
...
'First Page Service'
'Second Page Service'
'Third Page Service'
>>>for service in services:
...   service.service_url
...
'first_page'
'second_page'
'third_page'
但在这种情况下,同一行返回一个内部服务器错误


编辑:解决了这个问题,服务列表中的我的一个页面没有在routes文件中声明

如果在jinja模板中打印变量的值,则不需要使用单引号

从中,url_接受方法名称作为参数

下面是一个示例,我们如何将url_中的变量值用于模板中的方法

app.py:

url_for_example.html:

输出:

回家路线:

单击第二页URL后:

from flask import Flask, render_template, url_for, request


app = Flask(__name__)

@app.route('/first')
def first_page():
    return 'First page'

@app.route('/second')
def second_page():
    return 'Second page'

@app.route('/third')
def third_page():
    return 'Third page'


@app.route("/", methods=["GET"])
def home():
    services = [
    {
        "service_url": "first_page",
        "service_name": "First Page Service"
    },
    {
        "service_url": "second_page",
        "service_name": "Second Page Service"
    },
    {
        "service_url": "third_page",
        "service_name": "Third Page Service"
    }
    ]

    return render_template("url_for_example.html", services=services)
<html>
<head>
  <title>Dynamic URL Example</title>
</head>
<body>
    <ul>
    {% for service in services %}
        <li>
            <a href={{ url_for(service.service_url) }}>{{service.service_name}} </a>
        </li>
    {% endfor %}
    </ul>
</body>
</html>