2

What's the general Software Engineering rule of thumb again for frontend templating code?

If I look at certain websites, I notice some code smells in PHP such as:
$.modal = <?php echo $(base)["username"] != 'me' ?' ': echo 'style="display=none"' ?>

or just in general places in the code where PHP gets used as a templating engine for gluing together pieces of HTML code based on conditionals spread out over the codebase and the database itself too. To make things worse, this carries over to JavaScript ajax functions. As a developer, this to me just seems like spaghetticode.

On the other hand, many popular frameworks properly do templating, such as EJS, containing templating in one place and not mixing it with logic too much but just having simple output like <%= %>.

I know I've seen frameworks like Angular 1 contain pieces of HTML into directives, but maybe that's something different, more 'OO'-simulating or cleaner.

Comments
  • 2
    PHP 5.4 introduced <?= as a short tag for echo. Which should be used as it is way more readable.

    Imho every page that just renders via stream out html is broken.

    I know that many shops, e.g. Magento, still do this...

    Template engines exist for a reason. Not only because they make a lot of sense security wise, but because they reduce the danger of sprinkling code duplication everywhere. Typical examples are e.g. number formatting / encoding / ...

    Without a templating engine it is very easy to do it the wrong way and introduce several different formattings etc. into the page

    The other thing, which seems to be less popular in many JS frameworks, is separation of concerns.

    I am fond of MVC... Instead of "page renders all".

    Last but not least... Security.

    It's easy to overlook e.g. encoding values properly - things that any template engine should have built in
  • 3
    It's fine for some simple scripts. Not including the JS + database sprinkle. They should be functions or classes in different files. Using it as a template with some display code and some variables logic at the top is readable and convenient if you have a single or two page app.
  • 4
    It's not up to the templating engine to extract logic from templates, that's the job of the template author.
Add Comment