Jump to content


Splitting header includes

  • Please log in to reply
1 reply to this topic

#1 Amplivyn

  • Members
  • PipPip
  • Member
  • 26 posts

Posted 23 April 2013 - 10:26 AM

Surely most people here use a header php file that they include in the top of most pages in a website. I was wondering, does anyone else split them into two header files to leave editable space between the <head> tag so you can include CSS/JS scripts for some pages that most of the others don't require? For example, I might have a single page that requires jQuery or a special CSS file for the home page, etc. If this is a bad idea, is there a better practice out there? I'd rather not include some files in all the pages.

#2 kathas

  • Members
  • PipPipPip
  • Advanced Member
  • 113 posts

Posted 23 April 2013 - 03:20 PM

Actually I think the best way to solve this problem is through template inheritance.


Template inheritance allows you to extend templates and replace parts of the parent's content. You can see a very good example in Twig's documentation.


It is not necessary though to use twig or any template engine, you can implement similar behavior in plain php templates (although not as good looking). For example one could use anonymous functions to achieve similar block based inheritance.

--- Template base.php ----
<?php $main = function($head,$body) { ?>
    <?php $head() ?>
    <?php $body() ?>
<?php } ?>

<?php $head = function () { ?>
    <style> ... </style>
<?php } ?>
<?php $body = function () { ?>
  ... body ...
<?php } ?>

--- Template derived.php ---
<?php include ('base.php'); ?>

<?php $head = function () use($head) { ?>
    <?php $head(); ?>

   <script> ... </script>
<?php } ?>

<?php $main($head,$body); ?>

Edited by kathas, 23 April 2013 - 03:20 PM.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users