squirrellyjs / squirrelly

Semi-embedded JS template engine that supports helpers, filters, partials, and template inheritance. 4KB minzipped, written in TypeScript ⛺
https://squirrelly.js.org
MIT License
555 stars 81 forks source link

[ Feature ] - Preventing null and undefined exception on template variables #246

Closed Javiani closed 10 months ago

Javiani commented 1 year ago

Hi All! First of all, thanks for this amazing project, I was looking for something like this to use in my web component library, called Jails, you can find more info here: https://github.com/jails-org/Jails

The Problem

This PR tries to solve a problem that was making it impossible to use in my project, which is the fact that you might not have a variable already set used on iteration and conditions, so on those cases it breaks the entire application instead of returning null or false. I believe that Mustache already have this behavior by default, if you try to use some variable that doesn't exist it just skip it and treat as a falsy / empty value.

The Solution

try/catch is the only solution I've could think to solve that problem, so I wrap all variables with a function that tries to return that variable if it is set and return an empty string otherwise.


I didn't have time to look for all edge cases and I still not familiar with the entire code, and I'm not sure how much it's going to impact on performance, so maybe there's a better way, but I'll be glad if my PR could be usefull somehow even if it can't be merged.

Thanks in advance! Have a good one.

nebrelbug commented 1 year ago

@Javiani I think a better solution might be writing a custom helper to perform the same functionality.

Javiani commented 10 months ago

Nice, that was actually a desperate move from my side, not a good PR I admit. Thanks @nebrelbug, I didn't know it could be done using custom helper! That's way more better