Amplivyn Posted April 23, 2013 Share Posted April 23, 2013 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. Quote Link to comment https://forums.phpfreaks.com/topic/277201-splitting-header-includes/ Share on other sites More sharing options...
kathas Posted April 23, 2013 Share Posted April 23, 2013 (edited) 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 April 23, 2013 by kathas Quote Link to comment https://forums.phpfreaks.com/topic/277201-splitting-header-includes/#findComment-1426120 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.