Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> First, resist the urge to put code in your templates

Unless things have changed since I last looked, PHP files are all templates. Last time I used PHP, with symphony, I actually thought PHP was a pretty reasonable templating system.



PHP files are all templates, and when used properly they're relatively good at it. The problem is that, since there's no built in concept of separation, you have to enforce it yourself.

A lot of code written by beginners (myself included, once) will put business logic as close to where it will eventually be rendered as possible, so you end up with code that looks like this

    <ul>
      <?php
      // Thirty lines of database calls and string manipulation
      foreach ($results as $result): ?>
        <li><?= $result ?></li>
      <?php endforeach ?>
    </ul>
which makes intuitive sense but quickly leads to an unreadable template. It turns out that, even though you're writing these together, you'll rarely actually want to change them together. So you eventually learn to have template files and nontemplate files.

The .php vs .phtml distinction has no relevance to the compiler. They're only really useful to a human in making that template/code distinction explicit.


so, just choosing a random file off github, is this a template?

https://github.com/symfony/Process/blob/master/PhpProcess.ph...

Or in other words, php files are only templates if you use them that way.


If I have, say, a jinja2 template that only contains logic and outputs nothing, is it a template? I would say it is. By which reasoning, yes that php file is also a template. Even if you've got used to pretending it isn't.

Having said which, I'm confused by the lack of a closing ?>. Maybe PHP's parser lets you get away with that though.


Having said which, I'm confused by the lack of a closing ?>. Maybe PHP's parser lets you get away with that though.

It's completely optional.


...and best practice is to omit it. Since PHP is a templating language any whitespace (other than a single newline) that comes after the ?> will be printed directly to stdout when the file is parsed, which is almost never what the author intends. Letting the parser insert it for you avoids this class of bugs.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: