Jump to content

Splitting header includes


Amplivyn

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.