PHP - 最佳实践 - 网站模板[关闭]

I just wanted to see if the way I am constructing my website templates was the best and most dynamic way of doing it. Currently I have my website playout however for the areas that I want the content to change I use the following code.

<? 
 if (preg_match("/\W/",$page) || !file_exists("../$page.html")) {
  include("../home.html");
 }
 else {
  include("../$page.html");
 }
?>

The navigation then links to that page by saying something like,

<a href="index.php?page=about">About</a>

Is this the best way to construct a template using PHP or are there better ways? Thankyou for the help.

There is no best or most dynamic way of creating website templates.

All you can do is learn from experience and others.

Your code is one way to switch between templates. Some immediate improvements could be:

  • Use && instead of || because of short circuiting properties of the AND operator. If the page does not match then there is no need to do the file check

  • Use a array lookup table to map page value to filename template (e.g. 'home'->'homepage.html' etc.), mainly this helps in preventing serious exploits where external input is used for file paths.

  • Don't file check because why have a link with a non existent template?

Instead of writing from scratch like this (and IMO not so beautiful or dynamic as well), you better take a look at how frameworks do it. Most frameworks have (good, beautiful, dynamic, scalable, whatever) templating mechanism, both still in pure PHP or using 3rd party engine.