HowTo: Insert additional rows in the HEAD of a template file

Remark:

The source code of the following (extended) header file is based on Kirby version 2.1.0.
But you can use this solution for all older versions of Kirby.

Step 1:

Replace your snippet ‘header.php’ in the snippets directory by the extended version:


<?php if (!isset($header_include)) $header_include = ''; // no "header" extension required ?>
<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0">

  <title><?php echo $site->title()->html() ?> | <?php echo $page->title()->html() ?></title>
  <meta name="description" content="<?php echo $site->description()->html() ?>">
  <meta name="keywords" content="<?php echo $site->keywords()->html() ?>">

  <?php echo css('assets/css/main.css') ?>

<?php if($header_include <> ''):  snippet($header_include); endif; ?>
</head>
<body>

  <header class="header cf" role="banner">
    <a class="logo" href="<?php echo url() ?>">
      <img src="<?php echo url('assets/images/logo.svg') ?>" alt="<?php echo $site->title()->html() ?>" />
    </a>
    <?php snippet('menu') ?>
  </header>

Hint: Only the very first line and the line before </head> are new.

Step 2:

If you need some lines in the <head> of an template, build another snippet file (e.g. ‘header_include_fancybox.php’) in the snippets directory only with the extra lines.
Then change the line

<?php snippet('header'); ?>

in the template file to:

<?php snippet('header', array('header_include' => 'header_include_fancybox')); ?>

If you don’t need additional lines in the <head> of an template, change nothing in that template file.

That’s all!

Result:

  • The advantage of this method is that any rows can be inserted, depending on the needs of the respective templates.
  • If you want to add or change anything in the <head> of all of your webpages later, you only need to update one file (’header.php’) and still all pages are updated!

Pointer:

You can make this trick in the snippet footer.php, of course, mutatis mutandis.
And I would add the second supplement there on the line before </body>.

Good luck!

1 Like

Another couple of disadvantages to this approach is that you can only add one snippet, and you can’t add anything that isn’t a snippet.

A simpler solution would be to just assume that the variable will be a string.

if(isset($header_include)) {
    echo $header_include;
}

And when calling the header from your template you could use, for example:

snippet('header', array(
    'header_include' => snippet('fancybox_header', array(), true)
));

Or:

snippet('header', array(
    'header_include' => css('assets/css/carousel.css')
));
1 Like

@walkerbox:
Thanks for the good suggestions, I will take them over the next few days in my post.