Skip to content

Instantly share code, notes, and snippets.

@seeliang
Last active September 1, 2023 16:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seeliang/5675ae8606e6c1db5adee24cbe0306a0 to your computer and use it in GitHub Desktop.
Save seeliang/5675ae8606e6c1db5adee24cbe0306a0 to your computer and use it in GitHub Desktop.
use node to generate html from ejs file
const ejs = require('ejs');
const fs = require('fs');
module.exports = ({template, config}) => {
fs.readFile(template, 'utf8', (err, data) => {
if (err) { console.log(err); return false; }
var ejs_string = data,
template = ejs.compile(ejs_string),
html = template(config);
fs.writeFile(template.replace('.ejs', '') + '.html', html, (err) => {
if(err) { console.log(err); return false }
return true;
});
});
}
// const url = 'https://my.name.com';
// ejs2html({template:__dirname+'/src/index.ejs', config:{url}})
@Jeff-411
Copy link

This is great! Thanks.

It's just what I was after. Made my day. :)

I'm trying to build an Express app that will serve "User preference" forms to a static site that stores the preferences locally in the browser. It's been driving me a bit crazy.

But a quick test suggests something like the following should work with an app.get('/ejsForms/:file', (req, res) => {}) route:

const ejs = require('ejs')
const fs = require('fs')

const ejs2html = ({ input, output }) => {
  fs.readFile(input, 'utf8', (err, data) => {
    if (err) console.log(err)

    let string_ejs = data
    let convert = ejs.compile(string_ejs)
    let string_html = convert()

    fs.writeFile(output, string_html, (err) => {
      if (err) console.log(err)
    })
  })
}

// let req_userPreferences = { , , ,}
let req_nameOfForm = 'fonts'
let input = `ejsForms/${req_nameOfForm}.ejs`
let output = `output/${req_nameOfForm}.html`
// res.sendFile(output)

ejs2html({ input: input, output: output })

Anyway, thanks again. This really helps.

~ J

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment