Search code examples
jekyllliquidcontent-security-policy

Jekyll: is it possible to use Liquid tags in a CSS file? ( Re: Content Security Policy compliance)


In a Jekyll page, I have the following inline style:

<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>

For preventing any CSP violation/error, in the header, I set the CSP as follows:

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

But I am still getting the following warning in a few browsers such as Google Chrome, and Microsoft Edge:

CSS inline styles should not be used, move styles to an external CSS file

Therefore, I tried to move the inline style to an external CSS file as follows:

  1. Added an empty YAML block to the beginning of the CSS file
  2. Added the following CSS style containing the Liquid tags:

.myClass { background-image: url({% if latest_post.image contains "://" %}{{ latest_post.image }}{% else %} {{site.baseurl}}/{{
latest_post.image}}{% endif %}); height:320px; }

However, the Liquid tags added to the CSS file are not processed. In fact, in the resulting HTML page, I don't see the background-image is not shown on the page accordingly.

I would expect to see the background image accordingly.

Is it possible to properly move that inline style, and those Liquid tags, to an external CSS file?


Solution

  • The entry SASS file can contain Liquid templating. SASS partials cannot. Here's an example file: https://github.com/jekyll/jekyll-sass-converter/blob/master/docs/assets/css/main.scss

    You could either create a SASS variable containing that value, or use it directly in the main SASS/SCSS file (the one with the triple dashes at the top - likely called main.scss):

    ---
    ---
    
    {% assign latest_post = site.posts[0] %}
    
    .myClass {
      background-image: url({% if latest_post.image contains "://" %}{{ latest_post.image }}{% else %}{{ site.baseurl }}/{{ latest_post.image }}{% endif %});
      height: 320px;
    }