gpt4 book ai didi

python - 将 url_for 分配给变量并将其用作 render_template 中的参数不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:22 24 4
gpt4 key购买 nike

我遇到了 url_for 的问题,我使用 html 代码构建索引页面,并将其放入views.py 中的变量中,该变量作为 render_template 函数中的参数传递,在索引页面中使用 {{ content }}我可以从函数中获取html代码并显示几乎所有数据,当页面在href中加载时我看不到正确的路线,但我看到<a href="url_for('detail')">而不是<a href="detail"> .

这是views.py

for dog in dogs:
url_detail = url_for('detail')
htmlDog = htmlDog + '<div class="col-lg-4 col-md-6 col-sm-12 mt-3">
<div class="animal_block mx-2"><img alt="animal image" src="' +
str(dog[6]) + '" class="img-fluid img-thumbnail" />
<div class="text-center">' + str(dog[0]) + '</div><div>Lorem ipsum dolor sit
amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut

labore et dolore magna aliqua...</div><div class="text-center">
<a href=' + url_detail + '>look detail</a></div><span
class="animal_id">1</span></div></div>'

def home():
return render_template(
"index.html",
content = htmlDogs,
)

I have to call some function to encode htmlDog or use something different of render_template?

谢谢

最佳答案

Flask的url_for依赖于请求上下文,你不能把它放在 View 函数之外,尝试将for循环移到home函数中。

此外,您应该使用 Jinja 语法直接在模板(index.html)中编写 for 循环,而不是在 Python 中加入 HTML 代码。例如:

<body>
{% for dog in dogs %}
Put your html code here.
You can generate URL like this: <a href="{{ url_for('detail') }}">
{% endfor %}
</body>

另外,请记住使用 render_template 传递 dogs 变量:

@app.route('/')
def home():
return render_template("index.html", dogs=dogs)

阅读Jinja documentation了解更多详情。

关于python - 将 url_for 分配给变量并将其用作 render_template 中的参数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55315758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com