开发者

What is the fastest way to get basic templating in PHP, a la Struts Tiles?

开发者 https://www.devze.com 2022-12-19 00:12 出处:网络
I\'m new to PHP, and I\'m looking to do what I\'d normally do with Struts Tiles in JSP. I\'m looking for something like:

I'm new to PHP, and I'm looking to do what I'd normally do with Struts Tiles in JSP. I'm looking for something like:

Template.php:

<html><body>
 <div class="header"></div>
 <div class="contents">
  <#insert sectionName="pageContents">
 </div>
</body></html>

Content.php:

<#template name="Template.php">
 <#section name="pageContents">
  <div>
   <?php doSomething(); ?>
  </d开发者_运维知识库iv>
 </#section>
</#template>

Such that a request for Content.php returns the contents of Content.php included into Template.php appropriately. I'm looking for the fastest solution in terms of minimal installation/configuration time.


Have a look at Smarty: Template Engine


I think Smarty might be a bit overkill in your case, since you ask for a basic PHP templating.

You could take a look at Lerdorf's article on the No-framework MVC framework or you could go for one of these template engines:

  • PHPTAL (although some aspects of the PHPTAL syntax is on the edge of insanity)
  • Twig
  • Savant3

Without knowing anything about Struts I think I'd check out Twig first. Although it is a fairly new project I think that it has some really nice features that you might be interested in.


You can use any number of php templating systems, but I'd recommend you use php's native capabilities. There's no additional performance overhead, and nothing to install or configure.

For instance to mimic the example above, you could do something like:

Template.inc:


<html><body>
 <div class="header"></div>
 <div class="contents">
  <?php print $pageContents
  //Or if your php installation supports short tags
  //<?=$pageContents?>
  ?>
 </div>
</body></html>

Content.php


<?php
  $something = doSomething();

  $pageContents = <<<CONTENT

<div>
  $something
</div>

CONTENT;

  include "template.inc";

Of course, there are lots of other ways of accomplishing the example above. That's another upside to using native capabilities - you can arrange and configure your own templating system to work the way you prefer.


Personally I've found every PHP templating overkill. The price of learning and keeping up with the templating engine is just too high. It's often much easier to do it in PHP, with enabled short (ASP-style) tags if you're into that.

If you want, you can wrap the PHP templating in a simple class yourself, or use this:

  • http://mariz.org/blog/2005/jun/21/the-php-native-template-engine/

Still want a "real template"? Check out H2O, it looks nice (but I still think it's overkill)

  • http://www.h2o-template.org/

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消