title: Templating in PHP done right ... how?
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>How do I solve this?</p>
  
  <p>Having looked around for a while there seem to be 2 ways to solve this:</p>
  
  <ol>
  <li><p>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).</p></li>
  <li><p>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?)</p></li>
  </ol>
  
  <p>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.</p>
  
  <p>Is there maybe another option? How have you solved this problem?</p>