2

I'm building a web app that relies fairly heavily on Ajax for its interactivity, and I want to get around the problem of having two versions of my HTML templates, to keep things DRY.

I came across a question here, template engine both for JS and PHP, which came up with a good answer, mustache. Then I remembered all the stuff I wouldn't be able to do, like Zend_View_Helpers, and other PHP reliant stuff.

My question is, are there any better solutions? Perhaps that would allow me to use Zend_View (or similar to output to a templating language), which would allow me the flexibility of PHP and its libraries, but the DRYness of a template language.

That, or another solution entirely that I haven't thought of. I'm sure this sort of thing has been done many times before, so are there any best practices (or bad ones).

Thanks

Community
  • 1
  • 1
Adam
  • 5,091
  • 5
  • 32
  • 49

1 Answers1

0

Whilst I am not entirely sure what you are attempting to do how about using the Twig project. You can pass objects into the template and access its properties and methods:

For convenience sake foo.bar does the following things on the PHP layer:

  • check if foo is an array and bar a valid element;
  • if not, and if foo is an object, check that bar is a valid property;
  • if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
  • if not, and if foo is an object, check that getBar is a valid method;
  • if not, and if foo is an object, check that isBar is a valid method;
  • if not, return a null value.

foo['bar'] on the other hand only works with PHP arrays:

  • check if foo is an array and bar a valid element;
  • if not, return a null value.

There is also a JS port of the Twig templating language.

Treffynnon
  • 21,365
  • 6
  • 65
  • 98
  • That's a step in the right direction, yeah. I'll look into that. I guess what I'm looking for is the ability to have 2 stage templates. PHP in the first, which outputs a language-agnostic template, in Twig, Mustache, etc.. Maybe that's a crazy idea, maybe it's not what I want at all? – Adam Jan 21 '12 at 13:42