More on Using Masterpages (Layouts) Patterns in Languages Like PHP

In a prior post, I wrote about using php to implement a simple version of layouts, or what are called masterpages in ASP.Net. In it I mentioned that you could go directly to the content part for ajax purposes. I want to show how to support that in a language like php when not using a framework.

I’m going to try to get back to posting more about solutions that apply to simpler sites. I think rightfully so, developers have been backing off the complexity of large frameworks for everyday web projects. Often times, with just a few lightweight tools, clean maintainable web apps can be created. Listen to this episode of hanselminutes: it happens to be about WebMatrix, but could be an advertisement for php, sinatra and more.

Let’s say that I wanted to link to an about page, and using the convention from the prior post, I have masterpage.php, about.php, and about_text.php. Any link that goes to about should look like the following:

<a href="about.php" 
      alt="About Page" 
      onclick="loadContent('about_text.php');">About</a>

So if the user has javascript disabled, they will be sent to about.php where they will see the full layout and content. But if the javascript works, then it will popup just the content in a modal dialogue. Note that you have to implement the loadContent function yourself. For an example, see the following jqModal post.


Finally, it’s worth knowing that on the ruby side (for example using sinatra), you can control whether you use a layout on the server side with the following code:

if request.xhr?
  erb :about, :layout => false
else
  erb :about
end

For more ideas, check out books like Real-World Solutions for Developing High-Quality PHP Frameworks and Applications, or discuss below if you have ideas for more posts about solutions for your next web project. Also, checkout other php posts and programming posts.