[英]How to link static files in django, if the path is provided by the context in html?
這是我的views.py
文件:
from django.shortcuts import render
def page(request):
css = 'temp/css.css'
return render(request, 'temp/index.html', {'css': css})
和templates/temp/index.html
文件:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static '{{ css|safe }}' %}">
</head>
<body>
Hello Page
</body>
</html>
和static/temp/css.css
文件:
* {
width: 100vw;
height: 100vh;
background: red;
}
頁面渲染后的源碼為:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/%7B%7B%20css%7Csafe%20%7D%7D">
</head>
<body>
Hello Page
</body>
</html>
但我期待
...
<link rel="stylesheet" type="text/css" href="/static/temp/css.css">
...
為什么它不工作? 有沒有辦法做到這一點? 如果路徑由 html 中的context
提供,如何鏈接 static 文件?
假設“css”是您的上下文變量,您應該能夠執行以下操作。 基本上去掉'css'變量周圍的引號。
<link rel="stylesheet" href="{% static css %}">
您應該將<link rel="stylesheet" type="text/css" href="/static/temp/css.css">
直接添加到您的 index.html 中。 這樣它就會自行處理,你不需要將它作為上下文傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.