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
571 stars 81 forks source link

Use passed data object as root #188

Closed jase88 closed 4 years ago

jase88 commented 4 years ago

Is your feature request related to a problem? Please describe. It seems unnecessary for template string authors to add a variable name for the given data object.

Describe the solution you'd like It would be great to use data objects without the need of a variable name:

var myTemplate = "Hi, my name is {{name}}";
Sqrl.render(myTemplate, { name: "Johnny Appleseed" });

This of course would make it impossible to access something like a global context, but this might be desired. It would be great to globally configure if a variable name is necesarry, e.g. via config

{
varName: '' // or null
}
nebrelbug commented 4 years ago

Hi @kerosin, thanks for the question!

This is possible by setting the configuration option useWith to true.

Example:

var myTemplate = "Hi, my name is {{name}}";
Sqrl.render(myTemplate, { name: "Johnny Appleseed" }, {useWith: true});

I should probably update the documentation to explain this :smiley:

Hope this helps!

jase88 commented 4 years ago

Hi @nebrelbug , thanks for your quick response :)

One thing I noticed if using useWith with true:

Sqrl.render('Hello {{name}}', {}, {useWith: true});

returns the global object if the corresponding key was not found on the object, although useWith is set.

nebrelbug commented 4 years ago

@kerosin yes, this is expected behavior. It makes it possible to use variables from helpers, like:

{{@each(it.somearray) => val, index}}
Display this
The current array element is {{val}}
The current index is {{index}}
{{/each}}

I'll make sure to explain this in the docs too :)