You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中AMP页面无法加载字体:能否用static标签引入字体?

Can I use Django's static tag for font loading in AMP pages?

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:

  1. 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 static tags will render as raw template code instead of valid file paths.

  2. Use AMP's required style tag
    AMP doesn't allow external stylesheets—all custom CSS (including @font-face rules) 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>
    
  3. Write valid @font-face rules with static tags
    The path inside {% static %} should be relative to your app's static directory. For example, if your Font Awesome brand fonts are stored at yourapp/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.

  4. Verify file accessibility
    Double-check that your font files are in the correct static subdirectory, and run Django's collectstatic command 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:58:11