我正在使用 Django 创建一个相当复杂的网站,我注意到一个奇怪的问题。
我的所有模板都扩展了相同的基本模板 (base.html
)。该基本模板看起来(类似于)如下所示:
{% load staticfiles %}
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'css/fonts.css' %}">
<link rel="stylesheet" href="{% static 'css/webStyleSheet.css' %}">
{% block head %}
{% endblock %}
</head>
<body>
<div class="wrapper">
{% block header %}
<div class="header">
<h1><a href="/">Title</a></h1>
<ul class="nav-bar">
<!-- nav bar content here etc etc-->
</div>
{% endblock %}
</div>
</body>
</html>
<!-- js relevant to the nav bar etc etc -->
{% block script %}
{% endblock %}
我的 fonts.css
文件声明了我的字体,例如:
/* latin */
@font-face {
font-family: 'Overpass Mono';
font-style: normal;
font-weight: 400;
src: local('Overpass Mono Regular'), local('OverpassMono-Regular'), url('../fonts/OverpassMono-Regular.woff') format('woff'),
url('../fonts/OverpassMono-Regular.ttf') format('truetype');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
在我的 webStyleSheet.css
中,我像这样实现这些字体:
:root {
--font-secondary: 'Overpass Mono', monospace;
}
/*the class I use for the nav-bar elements*/
.menu-button {
font-family: var(--font-secondary);
}
正如我所说,我在我的所有模板中都扩展了这个基础。问题在于,在某些扩展模板上,我得到了正确的字体(Overpass Mono),但在某些模板上,我得到了默认字体(等宽字体)。该模板正在获取 webStylesheet.css
,但未呈现正确的字体。通常,我认为这只是获取字体的相对路径的问题。但是,两个扩展模板都是兄弟。相关文件结构如下所示:
site
--views.py
--urls.py
--static
----css
------fonts.css
------webStyleSheet.css
----fonts
------OverpassMono-Regular.woff
------OverpassMono-Regular.ttf
--templates
----html
------template1.html (font works)
------template2.html (font doesn't work)
两个模板都是这样扩展的:
{% extends "html/base.html" %}
{% load staticfiles %}
{% load tags %}
{% block head %}
<!-- some included css and scripts only relevant to this template -->
{% endblock %}
{% block content %}
<!-- content -->
{% endblock %}
{% block script %}
<!-- js -->
{% endblock %}
我能辨别的两者之间的唯一区别是模板的呈现方式。其中一个模板使用我的 views.py
中的 View 呈现,另一个模板直接使用 TemplateView.as_view(templatename='html/template1.html')
。就像在 urls.py
中一样:
urlpatterns = [
url(r'^url1/$', TemplateView.as_view(template_name='html/template1.html'), name='template1'),
url(r'^url1/url2/$', views.view2, name='view2'), # (return render(request, 'html/view2.html', contextVals) from views.py)
]
还会出现其他一些奇怪的伪像。我正在使用的其他字体之一(用于导航栏中的主标题)适用于所有模板!我还有其他函数在 template1 上工作,但在其他函数上不起作用:比如 Boostrap 函数 .tab()
和 .modal()
,它们可能是相关的并且必须处理包含在此继承结构中的处理方式。
这与模板的呈现方式有关吗?还有什么可能导致该问题,我该如何解决?它把我逼上墙了!任何指导表示赞赏。
(注意,我查看了 this question,但这不是同一个问题)
最佳答案
Welp,经过更多的挖掘,我终于找到了答案。原来问题出在这里:
:root {
--font-secondary: 'Overpass Mono', monospace;
}
/*the class I use for the nav-bar elements*/
.menu-button {
font-family: var(--font-secondary);
}
我意识到它使用的字体实际上并不是默认的等宽字体:它是完全不同的字体。好吧,如您所见,我包括的其他样式表之一使用相同的字体变量名 (--font-secondary
)。至少这意味着它比原先想象的更容易修复,但它绝对不能解释我与 Bootstrap 函数有关的其他问题。无论如何,这解决了问题中的主要问题。
关于CSS 字体仅适用于从同一基础扩展的某些 Django 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47778960/