简体   繁体   English

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

[英]Pass variable to href template in Django 2

I have below function in my views.py Django 2 project and I am trying to pass the variable "stylefolder" from views.py to my base.html template in order to dynamically get the correct href in my link tag.我的views.py Django 2项目中有以下函数,我试图将变量“stylefolder”从views.py传递到我的base.html模板,以便在我的链接标签中动态获取正确的href。

Below is my current code:以下是我当前的代码:

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)

In the base.html file, I have below code.在 base.html 文件中,我有以下代码。

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

The problem is that when I look into the view:Source section of the page, I get as a result:问题是,当我查看页面的 view:Source 部分时,我得到以下结果:

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

Instead of below desired result:而不是低于预期的结果:

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

What should I change to get "/static/cryptoblog/style.css" in the href tag?我应该更改什么才能在 href 标记中获取“/static/cryptoblog/style.css”?

Since you are in a template tag , you should not add the double curly brackets {{ .. }} , you can use the variablename instead, like:由于您在模板标签中,因此不应添加双花括号{{ .. }} ,您可以改用变量名,例如:

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

The reason why you get /static/%7B%7B%20stylefolder%20%7D%7D is because this is the percent-encoding [wiki] of the '{{ stylefolder }}' string.你得到/static/%7B%7B%20stylefolder%20%7D%7D的原因是因为这是'{{ stylefolder }}'字符串的百分比编码[wiki] This is logical, since it looks like you passed a string literal :这是合乎逻辑的,因为看起来您传递了一个字符串文字

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

你可以这样做: href="/static/{{ stylefolder }}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM