Search code examples
phphtmltemplate-enginetemplating

Templating in PHP done right ... how?


Some years ago I created a small website in PHP that now has grown and as you can probably guess it's quite a bit of a mess. Although I do have a separate template that does the final outputing of the html, I still end up having do handle a lot of the html in the 'business logic' part of the code.

My main problem is that the page contains various widgets (like 'latest entries', ads, etc.) that change from page to page and thus their html-(template-)code can't be hardcoded into the template. In fact even the main-content-container is a widget since the page-structure (or layout) is always the same.

So I end up having an array with $templateData['mainContent'], $templateData['widget1'], $templateData['widget2'], etc. that is generated in the business-logic part of the code.

How do I solve this?

Having looked around for a while there seem to be 2 ways to solve this:

  1. The obvious way would be to use a dedicated template language with inheritance and includes like django does, but given how complex these languages are I'm not really willing to learn yet another one of them. Also what I noticed during the time I spend with django was that it's not particulary fast (especially because it tempts one to use that templating for css and javascript too).

  2. The other option would be to use the templating features that PHP itself provides. But that would mean that every widget would have its own php-template and would generate its html-code by including the template-file and trap the result using output buffering. Is this a good idea? Since I still end up with HTML inside of the variables inside the logic-part. Also, doesn't this abuse output buffering for something that it wasn't intended for? And what about performance? (where is the buffer that I'm writing/reading/flushing from? How expensive are calls to ob_* functions?)

From what I've seen there are advocates for both variants. Personally I like option 2 more (since it's sort of what I'm already doing), but the html-in-variables feels very wrong and I doubt wether I would be solving anything this way.

Is there maybe another option? How have you solved this problem?


Solution

  • Why not to let each widget just include it's template?
    So, you will have to just call widgets from your main template.