[英]How can I pass context data to sylesheet 'src' and image 'src' attributes?
我有一個_layout.html
模板,如下所示:
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
{% block linkcss %}{% endblock %}
<title>{% block title %}{% endblock %}</title>
<script type="text/javascript" src="{% static 'scripts/jquery-2.1.3.min.js' %}"></script>
{% block scripts %}{% endblock %}
</head>
<body>
{% block head %}{% endblock %}
<table class="page_content">
<tr>
<td>
<div id="content">
{% block content %}{% endblock %}
</div>
</td>
</tr>
</table>
</body>
</html>
頁面home.html
通過以下內容擴展了上述內容:
{% extends "generic/_layout.html" %}
{% load staticfiles %}
{% block title %}{{ cust_title }}{% endblock %}
{% block linkcss %}<link rel="stylesheet" type="text/css" href="{% static '{{ cust_stylesheet }}' %}" />{% endblock %}
{% block scripts %}
<script type="text/javascript">
</script>
{% endblock %}
{% block head %}
<table class="head">
<tr>
<td class="center">
<img src="{% static '{{ cust_header }}' %}">
</td>
</tr>
</table>
{% endblock %}
{% block content %}
<table class="content">
<thead align="center">
<tr>
<th colspan="3" style="text-align: center">{{ cust_message }}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
{% endblock %}
該視圖是通用的,因為代碼檢查路徑並獲取上下文數據和頁面...這是一個示例:
# customer configurations constants:
CUSTOMER_CONFIGS = {
'samplewebpage': {
'context': {
'cust_title': "Sample Customer Page",
'cust_stylesheet': "SampleWeb/style.css",
'cust_header': "SampleWeb/sample_header.png",
'cust_message': "Welcome to Sample Web Page"
},
'home': "SampleWebPage/home.html"
},
}
# generic view:
def index(request):
path = request.path.replace("/", "")
context = CUSTOMER_CONFIGS[path]['context']
page = CUSTOMER_CONFIGS[path]['home']
return render(request, page, context)
目錄結構:
cust_title
可以正常工作。 那么如何以相同的方式傳遞cust_stylesheet
位置和cust_header
圖像源?
實際渲染類似於以下內容:
<link rel="stylesheet" type="text/css" href="/static/%7B%7B%20cust_stylesheet%20%7D%7D" />
<img src="/static/%7B%7B%20cust_header%20%7D%7D">
正如@DanielRoseman在評論中所說, 您不能在其他標簽內調用標簽。 但是可以使用變量。 然后,您可以嘗試以下操作:
{% static cust_header %}
那應該正確打印您的字符串。
注意:@Gocht提供的方法是可取的,因為它利用了django設置。 盡管可能不太有利,但我僅將此答案作為另一種選擇 。
基於上面@DanielRoseman的評論-“您不能在其他標簽內調用標簽。” -我更改了客戶配置和相關模板,如下所示:
'samplewebpage': {
'context': {
'cust_title': "Sample Customer Page",
'cust_stylesheet': "/static/SampleWeb/style.css",
'cust_header': "/static/images/SampleWeb/sample_header.png",
'cust_message': "Welcome to Sample Web Page"
},
'home': "SampleWebPage/home.html"
}
# template tags change
<link rel="stylesheet" type="text/css" href="{{ cust_stylesheet }}" />
<img src="{{ cust_header }}">
基於這些更改,頁面將使用特定的style.css和標題圖片正確加載:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.