What is the industrial practice on how to separate html and php code in a web project? Using echos to generate html is considered bad but what is the standard way to achieve the sought separation? Using template engines like twig?
2
The general practice is to put HTML in a template.
A template contains minimum programming code: it’s mostly HTML, with calls to variables and basic loops and conditional statements. The reason for that is that putting too much programming code in templates would:
-
Make testing difficult,
-
Make the reading and changing of the template difficult: the template should be straightforward enough to be able to be modified with minimum risk of introducing bugs.
A template engine, such as Smarty, is then used to transform the template into real content.
There are several aproaches, the one hand, using templates from the server side like Smarty, Twig, etc. I don’t recommend this approach because you’re coupling your presentation code to the technology used in the server (like php, python, ruby, java, …).
The other approach is to use client side templates/frameworks for the view (like ember, angularjs, backbone, …). I recommend this approach due to the separation of concerns between view (html,css,js …) and server code or controllers (php/symphony, python/django, ruby/rails, java/spring …).
So between your server code and your client code, the uniq glue you’ve to put is the model object in Json format (or whatever format you need). This way, you can develop code in the view that is reusable by any kind of server code, and thus, you can develop your application logic with different server technologies.