Template engine for PHP + JS but

368 views Asked by At

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

1

There are 1 answers

1
Treffynnon On

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.