Django中AMP页面无法加载字体:能否用static标签引入字体?
Yes, you absolutely can use Django's static template tag to reference font files in your AMP page's styles—just make sure you follow AMP's strict rules for styles and fonts, plus a few Django-specific steps to avoid common pitfalls.
Step-by-Step Guide:
Load the static template tag first
At the very top of your AMP template, you need to include this line to enable Django's static file handling:{% load static %}Skip this, and your
statictags will render as raw template code instead of valid file paths.Use AMP's required style tag
AMP doesn't allow external stylesheets—all custom CSS (including@font-facerules) must live inside an inline<style amp-custom>tag. This is non-negotiable for AMP validation:<style amp-custom> /* Your font rules go here */ </style>Write valid @font-face rules with static tags
The path inside{% static %}should be relative to your app'sstaticdirectory. For example, if your Font Awesome brand fonts are stored atyourapp/static/webfonts/, your complete rule would look like this:@font-face { font-family: 'Font Awesome 5 Brands'; font-style: normal; font-weight: normal; src: url("{% static 'webfonts/fa-brands-400.eot' %}"); src: url("{% static 'webfonts/fa-brands-400.eot?#iefix' %}") format("embedded-opentype"), url("{% static 'webfonts/fa-brands-400.woff2' %}") format("woff2"), url("{% static 'webfonts/fa-brands-400.woff' %}") format("woff"), url("{% static 'webfonts/fa-brands-400.ttf' %}") format("truetype"), url("{% static 'webfonts/fa-brands-400.svg#fontawesome' %}") format("svg"); /* Add this AMP-recommended property to avoid layout shifts */ font-display: swap; }I filled in the missing font sources (TTF/SVG) to complete the rule and added
font-display: swap—a best practice for AMP to prioritize content visibility over font loading.Verify file accessibility
Double-check that your font files are in the correctstaticsubdirectory, and run Django'scollectstaticcommand in production to copy files to your static root directory. This ensures the generated URLs point to valid, accessible files.
Critical AMP Reminders:
- If you're serving fonts from a different domain than your AMP page, you'll need to set up proper CORS headers to avoid loading errors.
- Stick to only the fonts you need—AMP prioritizes performance, so excess fonts can slow down your page and fail validation.
Content of the question originates from Stack Exchange, question author Mr Panda

