Jump to content

Splitting header includes


Recommended Posts

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.

Link to comment
Share on other sites

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); ?>
Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.