Jekyll:是否可以在 CSS 文件中使用 Liquid 标签? (回复:内容安全政策合规性)

问题描述 投票:0回答:1

在 Jekyll 页面中,我有以下内联样式:

<div class="myClass" style="background-image: url({% if

latest_post.image contains "://" %}{{ latest_post.image }}{% else %}

{{site.baseurl}}/{{ latest_post.image}}{% endif %});

height:320px;"></div>

为了防止任何 CSP 违规/错误,在标头中,我将 CSP 设置如下:

style-src 'self' 'unsafe-hashes' 'sha256-GlN6IkeSF4fF9C8zesLvRQRzAe2/ztqCm4T50cOnYvY='

但是我在谷歌浏览器和微软Edge等少数浏览器中仍然收到以下警告:

不应使用 CSS 内联样式,将样式移动到外部 CSS 文件

因此,我尝试将内联样式移动到外部CSS文件如下:

  1. 在 CSS 文件的开头添加了一个空的 YAML 块
  2. 添加了以下包含 Liquid 标签的 CSS 样式:

.myClass { background-image: url({% if latest_post.image contains "://" %}{{ latest_post.image }}{% else %} {{site.baseurl}}/{{

latest_post.image}}{% endif %}); height:320px; }

但是,添加到CSS文件中的Liquid标签没有被处理。事实上,在生成的 HTML 页面中,我没有看到背景图像相应地没有显示在页面上。

我希望相应地看到背景图像。

是否可以将内联样式和那些 Liquid 标签正确移动到外部 CSS 文件?

jekyll liquid content-security-policy
1个回答
0
投票

因为 CSS 文件是静态文件,所以不可能在外部 CSS 文件中使用 Liquid 标签。

解决方法一:可以将内联样式移到HTML文件头部,使用Jekyll的样式标签

<head>
  <style>
    .myClass {
      background-image: url(
        {% if latest_post.image contains "://" %}
          {{ latest_post.image }}
        {% else %}
          {{site.baseurl}}/{{ latest_post.image }}
        {% endif %}
      );
      height: 320px;
    }
  </style>
</head>
<body>
  <div class="myClass"></div>
</body>

解决方法 2:您可以使用 JavaScript 来应用动态样式。这确保在将 CSS 代码添加到文档之前处理 Liquid 标签。

<head>
  <style>
    .myClass {
      height: 320px;
    }
  </style>
  <script>
    window.onload = function() {
      var latest_post_image = '{{ latest_post.image }}';
      var site_baseurl = '{{ site.baseurl }}';

      var myClassElements = document.querySelectorAll('.myClass');
      for (var i = 0; i < myClassElements.length; i++) {
        var backgroundImageUrl = latest_post_image.includes("://") ? latest_post_image : site_baseurl + '/' + latest_post_image;
        myClassElements[i].style.backgroundImage = 'url(' + backgroundImageUrl + ')';
      }
    }
  </script>
</head>
<body>
  <div class="myClass"></div>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.