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
634 stars 83 forks source link

Question: renderFile usage - or how to load external template file #208

Closed LukaszGrela closed 4 years ago

LukaszGrela commented 4 years ago

I am trying to use the squirrelly 8.0.8 to render my template, I want to load the template from a location. I found the renderFile that is promising method which I used like that:

import * as Sqrl from 'squirrelly';
// template is  a path to a template file, data contains model for the template
      (Sqrl.renderFile(template, data) as Promise<string>)
        .then((compiled): void => {
          console.log('squirrellycompiled', compiled);
        })
        .catch(console.error);

but this fails with the squirrelly__WEBPACK_IMPORTED_MODULE_3__.renderFile is not a function error, what am I doing wrong?

The console.log(Sqrl); reveals following object: image and it indeed doesnt contain the renderFile function. How then one can load an external html file to use with squirrelly?

LukaszGrela commented 4 years ago

It's about built in functionality:) as I can fetch a template file and feed it into Sqrl.render

nebrelbug commented 4 years ago

Hi @LukaszGrela, good question!

Unfortunately, you can't use renderFile in a browser -- it's just for use in NodeJS. There isn't built-in functionality right now to render external files from a URL.

LukaszGrela commented 4 years ago

Thanks for your response, this is what I've made up to use. Thanks.

  public renderFile(
    templatePath: string,
    scope: object
  ): Promise<string | Error> {
    return Axios.get(templatePath)
      .then(
        (response: { data: string }): Promise<string> => {
          console.log('renderFile', response.data);
          const compiled = Sqrl.render(response.data, scope);

          return Promise.resolve(compiled);
        }
      )
      .catch(
        (error: Error): Promise<Error> => {
          console.log('renderFile', error);
          return Promise.reject(error);
        }
      );
  }

or async version

  public async renderFile(
    templatePath: string,
    scope: object
  ): Promise<string | Error> {
    try {
      const response = await Axios.get(templatePath);
      console.log('renderFile', response.data);
      const compiled: string = Sqrl.render(response.data, scope);
      return Promise.resolve(compiled);
    } catch (error) {
      console.log('renderFile', error);
      return Promise.reject(error);
    }
  }
nebrelbug commented 4 years ago

@LukaszGrela glad you were able to get something working :smiley: