简体   繁体   中英

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.

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.

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

The problem is that when I look into the view:Source section of the page, I get as a result:

 <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?

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  %}" 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. 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 }}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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