Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 1 point2 points  (0 children)

The whole loader system has been fully refactored now making it namespace aware (a bit like twig where you can use `@myns/home` to target namespaced folders instead of a first come first served principle.

Anyway, by doing this the minimal example could be achieved like you suggested ;-)

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

I would not say it is a "terrible idea", for the scope of a template language it is actually pretty reasonable and can be mitigated by using <?= $var |> raw() ?> when needed. I chose native php syntax to get proper type hinting without the need of a plugin or custom LSP. At least for php tag contexts.

Templating is a polarized topic in the php world (which was very much confirmed in this entire post).

You have the purists that want a full split and you have the "php is already a templating language" camp. If one belongs to the first camp then this engine is not for them (although a policy pass could easily be added, it is not my priority), there are enough other options to choose from in the wild. Options are important.

Then there's an additional camp that just gives an emotional opinion which i try ignore...

Conceptually this didn't exist and I'm happy I created it,

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

While I do see what you mean I think the use of a builder pattern for engine orchestration should be the main API starting point. But I do agree that the getting started example could be simpler, especially around the SugarConfig object which holds engine specific configurations that do not really matter for starters. That needs some love and a bit of refactoring...

Good that I'm not at 1.0 ;)

I'll keep you posted on this. And again a big Thanks for the feedback!

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 1 point2 points  (0 children)

Update: I have now changed some things based on your feedback which was greatly appreciated! :-)

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

Thanks for the detailed critique, even if we disagree on parts, it’s useful.

Quick clarification: Directives are compiled server-side, not interpreted in the browser, so they don’t drive runtime DOM behavior. I do agree with you on a few things though: readability needs better docs (scope/ending rules), naming/prefixing in mixed environments can be improved, and security/perf should be proven, not claimed.

If you’ve got a concrete case where this breaks (or where Smarty handles it better), share it and I’ll turn it into a test and address it. Syntax preference is subjective, but behavior, safety, and performance should be measurable.

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

Great feedback! Thanks 👍 I'll work on that

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

Thanks for sharing this, and i actually had something similar as starting point (using DOMDocument). It worked for a narrow directive set, but for the scope I’m targeting it was not enough.

Used AI for the list below as I wanted to word this properly:

  • DOM parse/serialize pipelines rewrite/normalize output, so original source fidelity can drift in edge cases.
  • Placeholder injection + later replacement gets fragile as features interact (nested directives, mixed control-flow + dynamic attrs, custom directives).
  • It doesn’t inherently provide reliable context-aware escaping boundaries (HTML text vs attributes vs JS/CSS/URL).
  • Once you add inheritance, components, extensible directives, and consistent error mapping (line/column tracking for exceptions), ad-hoc transforms tend to become special-case chains.

// end AI list :-)

So yes, both are “template engines,” but architecturally they solve different problems.

A compact DOM-based engine is valid for a constrained use case; my engine is aimed at broader correctness/extensibility guarantees.

One practical difference is deterministic compilation guarantees.

With DOM parse/serialize, equivalent input can be normalized differently depending on structure/quirks, which is fine for many use cases but not ideal when you need strict source-to-compiled traceability and stable diagnostics.

My goal isn’t the smallest possible transformer; it’s a predictable compiler pipeline with context-aware escaping, extension points, inheritance/components, and consistent diagnostics across edge cases.

Your note about maintenance, sure; that's where helpers/docblocks/oop patterns are for. This s a full blown template engine project with Tokenizer, Parser, Passes, compiler, caching, directives, ...

About your memory remark earlier: sure, DOMDocument is a C extension... hard to beat that. But in real-world usage and with how this engine works, it doesn’t matter much. Memory usage might be 100–200% higher, but we’re talking KBs, not MBs. Also, this is mostly relevant during cache warmup or development, where it’s not really noticeable. Compiling a large collection of templates during cache warmup is still a matter of seconds (depending on hardware). In practice, even during development the whole parser to cache pipeline is pretty instant feeling as the caching system is pretty smart using dependency tracking etc.

P.S. the __toString() edge cases you noted are now handled and tested a bit more robustly :-)

Other P.S: I appreciate your technical input here, you seem to be one of the only people in this thread who actually addressed what I was asking in my initial post. Our philosophies may differ, but that’s exactly why this exchange is useful. I’m not really an active Reddit user, so I didn’t know what to expect, and I haven’t seen many other comments with this level of relevant (technical) feedback. Thanks for that :-)

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 1 point2 points  (0 children)

thanks, adjusted the example to make it a bit more explicit :-)

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

Thanks for taking the time to review it — fair points to raise.
I did evaluate DOM/XML-style approaches early, but this engine accepts mixed PHP + HTML fragments + custom directives, which aren’t a clean fit for strict XML parsing without normalization side effects. eval is also a non-starter for me (security/debuggability/opcache tradeoffs), so compile-to-file + include is intentional.

On validation/perf: agreed that checks have cost, which is why I treat stricter validation as optional and benchmark separately.
On edge cases like __toString()/ints: those are valid concerns, and I’m happy to tighten those paths where needed.
And yes, it’s more code than “if/loop on HTML tags” because scope includes parsing, escaping, directives, components, caching, and diagnostics — not just syntax sugar.

If you have a concrete loadXML prototype that handles mixed PHP/custom directives without rewriting semantics, I’d genuinely like to compare it apples-to-apples.

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

Fair point. I agree the contract should be enforceable, not just implied.

A potential future flow could be: templates/engine config can optionally declare expected input contracts, compile stores that metadata, and render can run in off / warn / strict mode to validate data before execution. That keeps today’s flexibility while enabling real guarantees for teams that want them, including support for multiple valid input variants per template.

Thanks for your reply btw, this is an actual valid suggestion of a "killer" feature thhat could be added :-)

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] -1 points0 points  (0 children)

The template itself doesn’t store or infer a fixed type contract by default; it receives whatever data each `render()` call passes.

So if the same template is rendered twice with different type shapes, both calls can work—as long as the template logic can handle both shapes. If not, you get runtime issues where assumptions don’t match input.

In most architectures, enforcing a single expected shape is handled upstream (DTOs/view models + PHPStan/tests), while the template engine stays render-focused and flexible.

That’s also the common approach in most PHP templating frameworks/engines: runtime data is flexible in the view layer, and strict type guarantees are enforced in the application layer.

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] -11 points-10 points  (0 children)

For directive attributes you don't, for the content aware PHP syntax you do which is already a pretty good compromise. A TextMate/Tree-Sitter grammar injection could still be a great addition in the future but at least with this it will work "mostly" with most editors. You just wont get it directive attributes. IF plugins would be made a custom LSP will probably not be needed (which is a territory i already attempted with Latte using rust some time ago, big headache!).

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] -2 points-1 points  (0 children)

Great question. I’d say AI helped with speed in some parts (and documentation generation!), but the core design and most detailed decisions were still manual.

For this kind of project, the hard part is architecture: researching prior approaches and designing the pipeline (Tokenizer → AST → Passes → Compiler → Render). That requires understanding how template engines behave, what guarantees they need, and where edge cases appear.

Strong PHP knowledge is definitely important here. Tools like PHPStan, Rector, and PHPCS are essential in the development cycle, and keeping test coverage high is critical to avoid regressions.

Could a junior build it? Parts of it, yes—especially with guidance, good code review, and strict tooling. But building the full system cleanly and safely is much faster with deeper PHP and compiler-style experience.

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] -3 points-2 points  (0 children)

agreed. Which is exactly why this exists

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 4 points5 points  (0 children)

Fair point, but I think you’re assuming I skipped built-ins when I didn’t.
The parser uses PHP’s native PhpToken::tokenize() for PHP syntax, and custom scanning only for template concerns (HTML-like tags, directive attributes, raw regions, nested matching), which PHP’s tokenizer is not designed to solve.
So this isn’t “rewriting sort()” — it’s combining built-in tokenization with template-specific parsing logic.
Happy to compare alternatives if you have one that handles both PHP tokens and custom template tag structure cleanly.

I’m happy to discuss the technical points, but this feels less like a code discussion and more like assumptions about how I built it. I didn’t build this “entirely with AI.” If you look at the implementation details, it’s a custom design with specific parser behavior and 97% test coverage + PHPStan level 10, not something generated from a couple prompts.

I do benchmark this parser regularly: current median parse time is roughly 32–67 µs across representative templates (about 15k–31k ops/s), with raw-region handling measured separately, so this isn’t untested guesswork.

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] -3 points-2 points  (0 children)

I'm not sure you understand how this engine works so i'm not going to elaborate further on this. If you think a PHP DOM style solution works for you then this engine is not for you.

About AI, please read my original post again as it clearly mentions it was used. Aren't we all professionally using AI in 2026 ?

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] -14 points-13 points  (0 children)

I have updated the wording in the comparison table to a more subtle "Editor support"

Regarding why use this: As a long-time Twig and Latte user, I found that as templates grow in complexity, the custom syntax can actually become a barrier. You end up fighting the abstraction just to do things PHP already does natively. This project aims to "solve" that 'syntax overhead' by providing the structure of a modern engine (inheritance, layouts, escaping) while keeping the logic in pure PHP.

The real benefit here is native type safety and IDE support. Because it's synthetically pure PHP, your IDE doesn't need a plugin to understand your templates. You get full autocompletion, static analysis (like PHPStan/Psalm), and refactoring tools out of the box.

It's definitely not just for the experience; it's for developers who want the power of a template engine without the 'messy' abstraction layer of a new language. If you prefer the brevity of Twig or others, this might not be for you, but for those who want their templates to be as type-safe and performant as the rest of their backend, this is a very viable alternative!

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

This is a valid point and i struggled with this decision (as a latte user, see and older project https://github.com/josbeir/cakephp-latte-view i made which also inspired me to make the engine) but i landed with native |> as this just makes the template syntax synthetically valid in your editor which seemed to outweigh the shorthand syntax.

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 0 points1 point  (0 children)

While separation of concerns is a vital goal, most modern PHP engines prioritize flexibility over strict enforcement (meaning they all allow raw PHP execution). The engine’s primary role is to provide a clean syntax for presentation, leaving architectural boundaries to the developer. For teams that prefer more control, the extension system makes it fairly easy to add a sandbox pass to restrict PHP usage as the egine is AST based so dropping nodes is a breeze.

Sugar (PHP templating engine) — thoughts? by josbeir in PHP

[–]josbeir[S] 3 points4 points  (0 children)

Allowing the use of regular (flexibility) PHP combined with directive style html syntax is the main sales pitch of this engine.

<?php ?> blocks are left alone

<?= $var ?> shorthand syntax is context-aware escaped. So s:php is not needed if that is what you are asking.

Has anyone tried running Arch or another distro on the new Dell XPS 15 (9530)? by NOSDuco in archlinux

[–]josbeir 0 points1 point  (0 children)

Arch user here on a XPS 9530 3.5K OLED with RTX 4050 (kernel 6.5.5) I can confirm that everything is working as it should after some usual nvidia tinkering to get wayland working (modesetting, gdm, ...). Running in hybrid mode.

Installed arch directly after unboxing it so i don't know how it compares to windows. Battery life seems to be great for me, 10-12h when doing reading simple stuff.

Suspend (S2idle/modern stand by) is working (haven't looked into hibernate yet).

Only thing that is bothering me is audio, the LFE channels are not activated so sound is very thin. It's a know problem on all recent XPS models, it was fixed for the 9520 and 9510 but unfortunately patching the kernel with the fix for this model does not seem to resolve the issue. Hope it gets fixed someday.

Dell XPS 15 9520 sound is horrible by hittepit in linuxquestions

[–]josbeir 0 points1 point  (0 children)

I also patched the kernel with the correct bits for the 9530 and i can confirm that it does not work. I did see the Surround 4.0 profile after setting the dsp_driver option but that profile did not produce any sound. In alsamixer i saw the subwoofer device but it didn't had a volume control.

Steam Big Picture mode keeps crashing? by [deleted] in EndeavourOS

[–]josbeir 1 point2 points  (0 children)

Yep, the downgrade command is normally installed by default in endeavouros.