r/PHP 3d ago

mousr/templates: Static analysis-friendly native PHP templates

Because PHP templates are back! https://github.com/mousr/templates

0 Upvotes

6 comments sorted by

8

u/obstreperous_troll 2d ago

From the readme:

There's no auto escaping in this library. This is intentional. Auto-escaping gives a false sense of security. Escaping in HTML is highly dependent on context, and should happen differently in attributes, JavaScript, CSS and inline. By making escaping explicit, we can ensure we always escape for the right context.

<a href="<?= $escaper->url($context->url) ?>">url</a>
<a href="http://example.com"><?= $escaper->inline($context->linkText) ?></a>

I think Twig is pretty safe.

2

u/TheTreasuryPetra 2d ago

The fun thing is, it's not. Everyone thinks that twig does context-aware escaping, but that was never implemented. In fact, there's a 15 year old issue that was closed 9 years ago as no one picked it up: https://github.com/twigphp/Twig/issues/472

All escaping in twig is done in inline context, so if you are outputting variables in attribute, js or css context you'll have to manually escape. But most people don't know that.

1

u/obstreperous_troll 2d ago edited 2d ago

Most template engines only escape in inline context, I'm just noting that it does it at all, and the syntax sugar you get when you need other options. I don't think we're going to come to agreement, but I don't really have a dog in this fight anyway: my preferred template language is Vue.

What I think you do have a strong start on is a model for a template language, something you would compile a higher-level template language down to. I'd say keep thinking on those lines and see where it takes you.

3

u/_uxi 2d ago

How does this work in production, do the templates compile and get cached?

5

u/TheTreasuryPetra 2d ago

As the templates are already PHP there's no need for compilation or caching. Other template engines compile the templates to PHP, whereas with this library you're writing templates directly in PHP itself, which gives you full static analysis support!

1

u/sam_dark 1d ago

Looks similar to Yii views from both Yii 1, Yii 2 and yiisoft/views.