简体   繁体   English

如果路径由 html 中的上下文提供,如何链接 django 中的 static 文件?

[英]How to link static files in django, if the path is provided by the context in html?

Here is my views.py file:这是我的views.py文件:

from django.shortcuts import render

def page(request):
    css = 'temp/css.css'
    return render(request, 'temp/index.html', {'css': css})

and templates/temp/index.html file: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>

and static/temp/css.css file:static/temp/css.css文件:

* {
    width: 100vw;
    height: 100vh;
    background: red;
}

After rendering source of the page is:页面渲染后的源码为:

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

but I am expecting但我期待

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

Why it is not working?为什么它不工作? Is there any way to do this?有没有办法做到这一点? How to link a static file if the path is provided by the context in html?如果路径由 html 中的context提供,如何链接 static 文件?

Assuming 'css' is your context variable, you should be able to just do the below.假设“css”是您的上下文变量,您应该能够执行以下操作。 Basically drop the quotes around the 'css' variable.基本上去掉'css'变量周围的引号。

<link rel="stylesheet" href="{% static css %}">

You should add <link rel="stylesheet" type="text/css" href="/static/temp/css.css"> to your index.html directly.您应该将<link rel="stylesheet" type="text/css" href="/static/temp/css.css">直接添加到您的 index.html 中。 That way it will take care of itself and you don't need to pass it as the context.这样它就会自行处理,你不需要将它作为上下文传递。

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

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