Jump to content


Photo

Splitting header includes


  • Please log in to reply
1 reply to this topic

#1 Amplivyn

Amplivyn

    Member

  • Members
  • PipPip
  • 26 posts

Posted 23 April 2013 - 05: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

kathas

    Advanced Member

  • Members
  • PipPipPip
  • 113 posts

Posted 23 April 2013 - 10:20 AM

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) { ?>
<html>
  <head>
    <?php $head() ?>
  </head>
  <body>
    <?php $body() ?>
  </body>
</html>
<?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 - 10:20 AM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com