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

When using sqrl.templates.define() I get an error #199

Closed futurelucas4502 closed 3 years ago

futurelucas4502 commented 3 years ago

Describe the bug A clear and concise description of what the bug is.

When using the following snippet of code:

Sqrl.templates.define("head", Sqrl.render("views/partials/head.squirelly"));

I believe the reason for this error is because here template is being defined as a variable and then template() is being called as if its a function however because we now have a function and a variable with the same name javascript interprets the word template as a variable and throws an error, therefore, I would suggest renaming the template function to templateFunc to fix this problem

Environment: Node

nebrelbug commented 3 years ago

@futurelucas4502 thanks for submitting this! I like the idea to name template to templateFunc.

Actually, though, the reason your code errors is because you should define the partial as a compiled template function, which you get using compile.

Here's an example that should work (though I haven't tested it)

var path = require("path")

var headPartial = fs.readFileSync(path.join(__dirname, "views/partials/head.squirrelly"))

Sqrl.templates.define("head", Sqrl.compile(headPartial))
futurelucas4502 commented 3 years ago

Now i get an error here as strng is now a buffer and not a string that can be manipulated using the following however does work:

Sqrl.templates.define("head", Sqrl.compile((fs.readFileSync(path.join(__dirname, "views/partials/head.squirrelly"))).toString()));
nebrelbug commented 3 years ago

@futurelucas4502 oops, I forgot that readFileSync returned a buffer. Glad you were able to get it working :smiley:

By the way, if you use {{@includeFile() /}}, you don't even have to register the partial ahead of time.

Example (again, off the top of my head, haven't tested it):

let template = "{{@includeFile('partials/head.squirrelly') /}}"

Sqrl.render(template, data, {
  views: [path.join(__dirname, views)] // Tell Squirrelly where to look for the templates
})
futurelucas4502 commented 3 years ago

Hi there that would make my code a lot neater thank you I'm going to implement that now

also if you're wondering why I'm having so many issues its because I'm building a template view renderer for electron

nebrelbug commented 3 years ago

@futurelucas4502 awesome, it looks really cool!