Art-directed blog posts

I've been asked by two beta testers if it is possible to add custom css and javascript to each page with Kirby, to create art-directed blog posts for example.

In fact it is very easy and a great way to create custom designs for individual pages without having to build additional templates. Here is how it is done:

In your content folder for your page or article, add a css file and/or a javascript file. It's totally up to you how you name them. I just use styles.css and scripts.js here.

You can even add multiple css and javascript files if you want but let's keep it simple for this example.

Afterwards go to the header snippet for your site
(by default this is site/snippets/header.php)

What we want to do is to include our stylesheet and script files in the head section of our html and it's just a few lines of code to do that.



<!-- custom css -->
<?php foreach($page->files()->filterBy('extension', 'css') as $css): ?>
<?= css($css->url()) ?>
<?php endforeach ?>

<!-- custom javascript -->
<?php foreach($page->files()->filterBy('extension', 'js') as $js): ?>
<?= js($js->url()) ?>
<?php endforeach ?>



What we are doing here is to get all files in our content folder and filter them by extension. This will result in a set of .css files and a set of .js files, so we use a foreach loop to load each of them. This means that we could easily have more css or js files if we want – oh wait I already said that before :)

css($url) is a handy little helper function, which will automatically take the passed url and build a proper css link for it:

<link rel="stylesheet" type="text/css" media="all" href="" />

js($url) does the same for javascript files:

<script type="text/javascript" src=""></script>

And that's it!! Now you got a very easy way to create art-directed posts or custom styles for individual pages.