1

I am new to PHP. How can I create a base (like an asp.net masterpage) and have all other pages inherit from the base page or designate that I want pages to inherit from a certain base page, so I don't have to recreate things like headers, navigation, footers, etc...

Is it just more or do ASP.NET Masterpages seem to slow things down and add unnecessary clutter?

Searock
  • 6,278
  • 11
  • 62
  • 98
Xaisoft
  • 45,655
  • 87
  • 279
  • 432
  • If you use MVC frameworks like Codeigniter, Yii, etc it is possible to achieve similar results, please see http://stackoverflow.com/a/3208300/92487 – Searock Jul 29 '12 at 12:19

5 Answers5

3

There is no such thing in php; however, there are 2 functions you can use to simulate that.

include() and require().

Like this

top.php

  <html>
<head>
<title>google<title>
<!--css and script includes-->
</head>
        <body>
<div id="top">
    <ul id="menu">
      <li><a>link</a></li>
    </ul>
</div>

Other.php

random text

The two constructs are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error.

Kimtho6
  • 6,154
  • 9
  • 40
  • 56
  • So I assume header.php would include markup for just a header and then I would put that in a header section for another page. Is that correct? – Xaisoft Mar 04 '11 at 12:42
  • What is the difference between include and require? and where would you put the stylesheet link for menu.php? – Xaisoft Mar 04 '11 at 13:40
  • One thing I noticed in your example is that menu.php doesn't actually contain any php code, so could this just be an html file and in the Other.php file, I can do something like or does it have to have the php extension. – Xaisoft Mar 04 '11 at 13:45
  • @Xaisoft, you new best friend: http://php.net If you want to lookup a function's documentation: `http://php.net/[functionName]` for example http://php.net/require – Jacco Mar 04 '11 at 13:47
2

Php doesn't have masterpages.

You can however create functionality for them.
Its not exactly a master template tho

Here is a simple example:

header.php

<!doctype><html><head></head><body>

index.php

<?php include 'header.php'; ?> // more html here // <?php include 'footer.php'; ?>

footer.php

</body></html>
1

I'd suggest you to use a template engine which supports features like inheritance. Using plain PHP for templates is a PITA.

Twig looks pretty nice and supports template inheritance: http://www.twig-project.org/

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

I don't know, what a masterpage should be - but normally your start with a single index.php, which includes all necessary libraries, files and also templates, which are used to format the output. To request a single page, normally you use a request-parameter on that index.php.

feeela
  • 29,399
  • 7
  • 59
  • 71
-1

There is a VERY nice way using functions:

ob_start();
ob_get_contents();
ob_end_clean();

See an example

Eonasdan
  • 7,563
  • 8
  • 55
  • 82