How to use the base url in sass?

The situation

I want to create a @font-face like:

@font-face {
  font-family: "Noto Sans Symbols";
  src: url('/noto.woff2') format('woff2');
  font-display: swap;
}

However, my blog will be hosted on GitHub in a subpath, like ccjmne.github.io/blog.
For that reason, /noto.woff2 isn’t a valid path once deployed… but is correct while iterating with zola serve.

  • In html templates, I can use {{ get_url(path=”/noto.woff2") }}.
  • In markdown content, I can use a shortcode to the same effect.
  • In sass? I’m not sure how it’s achieved.

I tried setting css variables in my base.html:

    <style type="text/css">
      :root {
        --url-font-noto: url("{{ get_url(path="/noto.woff2") }}");
      }
    </style>

But that still doesn’t quite work: css vars do not get interpolated within @font-face blocks.

Because of the way I set up my @font-face, I really don’t want it all done in an inner <style type=”text/css”> child of some html template, I’d much rather keep working with sass directly.

Is there really currently no way to refer to the base url from sass?

Proposal

If there is indeed currently no such way, would it be possible to inject either sass variables, like $base-url, or sass mixins, like get_path, which’d be available in our sass files?

I suspect we could prepend some custom sass string to the grass.rs processor.

If the proposal seems good to you, I could try my hands at submitting a PR that injects $base-url and update the documentation accordingly. What do you think?

I haven’t used sass, in Zola or otherwise, but relative URLs in CSS are interpreted as relative to the stylesheet file. If Zola puts sass output in public/css,and your fonts are copied from static to public, does url('../noto.woff2')give you what you want?

Zola seems to frown on relative URLs, possibly because they don’t work in feeds, but feedreaders generally ignore CSS files and custom fonts anyway.

1 Like

Woah, that’s quite possibly the most obvious and simple solution, yet I somehow hadn’t even considered it.
Yep, a relative path works perfectly here. Thank you @mrec!

1 Like