Save custom css to a file

Hi,

Happy new year! :slight_smile: Back to Kirby even though I didn’t stop :smiley:

I have a “Custom CSS” field and the output is added to the header of that page. I’m wondering if it’s possible to save that content to a .php or .css file and link to it instead?

1 Like

That should be possible, yes, but what exactly would be the advantage?

You could, for example, use a page.update:after hook that writes to a css file. Personally, I’d try to avoid having editors mess with CSS, if they don’t know what they are doing, they can mess up the whole site.

Happy new year to you as well!

Thanks! page.update:after looks interesting. For now I will keep the CSS in the header.

The main advantage would be to clean up the header from all CSS. Currently the user can customize a lot of things from the panel, add custom backgrounds, change fonts, heading sizes… I was thinking to aggregate all CSS bits into one file instead.

If you want to try it, you can write to a file like this (assuming the custom CSS is stored in the site in a single field, so we use `site.update:after):

    'hooks' => [
        'site.update:after' => function($site) {
      
          $css = $site->custom_css_field()->value();
          F::write(kirby()->root('assets') . '/css/custom.css', $css);

        }
    ]

The example assumes, that the editor actually writes CSS into a field. If you store single values in different fields, you would of course have to create valid CSS first, then store all that in the file.

2 Likes

This looks awesome!

When writing the file, is it possible to add a random string at the end? For cache purpose.

F::write(kirby()->root('assets') . '/css/custom.css?ver=1234567', $css);

No, that doesn’t make sense. That string should be added via cache busting in your template, not as part of the filename.

Ok thanks, will take a look. The thing is the ver number should only be updated when the file is updated. Like ver=1234 until the user saves the custom css field and it becomes ver=1235.

You should then update the file only when changes have been made.

From the fingerprint readme:

Hash and SRI values are cached and only updated when original file is modified.

You can, of course, also add a version number to the stored CSS file (custom-v12345.css). But then you have to use logic in your header that finds the new file (and make sure to delete all the old files once in a while)

I found a really simple way to solve this without the plugin.

<?php
if ($site->customCss()->isNotEmpty()):
  $ver = filemtime("assets/css/custom.css");
  echo css(['assets/css/custom.css?ver=' . $ver . '', '@auto']);
endif;
?>
3 Likes

Sorry to hijack this old thread, but how would you go about creating a css file if you have a number of single values in your site.yml file?