Hacker News new | ask | show | jobs
by smt88 4087 days ago
I used to think PHP was good for templating, but then I learned about code-less templating engines like Jinja, and I'll never go back.

When you use a templating engine, you can change the backend entirely without messing with the template. You can also compile/optimize the display of data in the template more easily.

Some awesome person has made a Jinja2 lib that comes with Rust bindings, which looks cool (though I haven't tried it yet): https://github.com/jroweboy/jinja2-c

1 comments

> When you use a templating engine, you can change the backend entirely without messing with the template. You can also compile/optimize the display of data in the template more easily.

To be fair, all that you can do with a templating engine you can do "natively" as well. You can for example have code-less templates in PHP if you are disciplined enough to keep it that way. The only thing template engines do is enforce not being able to shoot yourself in the feet, but it's not an absolute must if you know what you are doing.

Sorry, should have clarified "code-less". I definitely don't like logic in templates (although React is making me re-think that as a strict policy). But I actually meant code as in any code. A line in PHP might be this:

    <a href="<?php echo $some_url ?>">Some link</a>
So that "echo" is the code. And the same thing in Jinja is this:

    <a href="{{ some_url }}">Some link</a>
In Jinja, it's only HTML + the names of variables (which I guess you could call "data"). I can now take that line and use it with any language that supports Jinja-style syntax (PHP, Node, Python, etc.) It's also not unlikely that a designer will know it.

Also, sometimes when you use PHP, you have to sacrifice correctness or speed for readability. You don't have that problem when you're running templates that were compiled to PHP, rather than hand-written PHP.

Finally, template inheritance is absolutely amazing. Can't live without it now.

For the record, your first example can be written in this manner with short tags on:

    <a href="<?=$some_url?>">Some link</a>
Which is effectively pretty close to a templating pseudo-syntax.
That's a perfect example of a bad practice that's done for readability in PHP templating.

Short tags are off by default in PHP (and have been for years), so you're losing some portability when you use them in your code. If, for example, someone reinstalls your PHP package and overwrites your config (which is very easy to do), your app suddenly breaks.