gpt4 book ai didi

python - 将变量传递给 Django 2 中的 href 模板

转载 作者:行者123 更新时间:2023-12-02 16:55:51 25 4
gpt4 key购买 nike

我的 views.py Django 2 项目中有以下功能,我试图将变量“stylefolder”从 views.py 传递到我的 base.html 模板,以便在我的链接标记中动态获取正确的 href。

下面是我当前的代码:

def home(request):
products = Product.objects.order_by('-votes_total')
paginator = Paginator(products, 10)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)

context = {
'products':paged_listings,
'stylefolder': 'cryptoblog/style.css'
}
return render(request,'home1.html', context)

在 base.html 文件中,我有以下代码。

href="{% static '{{ stylefolder }}' %}">

问题是,当我查看页面的 view:Source 部分时,我得到的结果是:

 <link rel="stylesheet" type="text/css" href="/static/%7B%7B%20stylefolder%20%7D%7D">

而不是低于期望的结果:

 <link rel="stylesheet" type="text/css" href="/static/cryptoblog/style.css">

我应该更改什么才能在 href 标签中获取“/static/cryptoblog/style.css”?

最佳答案

因为你在模板标签中,你不应该添加双大括号{{ .. }},你可以使用变量名来代替,比如:

<link href="{% static <b>stylefolder</b> %}" rel="stylesheet" type="text/css"">

你得到 /static/%7B%7B%20stylefolder%20%7D%7D 的原因是因为这是 percent-encoding [wiki] '{{ stylefolder }}' 字符串。这是合乎逻辑的,因为看起来你传递了一个字符串literal:

>>> from urllib.parse import unquote
>>> unquote('/static/%7B%7B%20stylefolder%20%7D%7D')
'/static/{{ stylefolder }}'

关于python - 将变量传递给 Django 2 中的 href 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56468267/

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