From 439c1e4a3b3ecae60ed6162f6fdc8d575d498152 Mon Sep 17 00:00:00 2001 From: Enzo Testa <98805541+enzoclock@users.noreply.github.com> Date: Wed, 20 Mar 2024 11:19:00 +0100 Subject: [PATCH] docs: define ETA engine in Express walkaround --- docs/resources/express.md | 73 ++++++++++++++++++++++++++++++--------- 1 file changed, 57 insertions(+), 16 deletions(-) diff --git a/docs/resources/express.md b/docs/resources/express.md index a518bda..9eecf4f 100644 --- a/docs/resources/express.md +++ b/docs/resources/express.md @@ -7,28 +7,69 @@ Eta no longer supports the Express.js `app.engine()` function, but it's still co ```js const express = require("express") -const app = express() -const path = require("path") -const port = 3000 +const path = require("node:path") +const { Eta } = require("eta") -var { Eta } = require("eta") +const app = express() -// views directory -let viewpath = path.join(__dirname, "views") -// on Deno, use let viewpath = Deno.cwd()+'/views/' -let eta = new Eta({ views: viewpath, cache: true }) +const eta = new Eta({ + // Views directory path + views: path.join(__dirname, "views"), // on Deno : `${Deno.cwd()}/views/` -/* no more needed with Deno or Node (Eta v3.x.x) -app.engine("eta", eta.render) -app.set("view engine", "eta") -*/ + // Any other option... + cache: true +}) app.get("/", (req, res) => { - // use status(statusNumber) and send(template) - res.status(200).send(eta.render("index", { title: "Hey", place: "Hello there!" })) + const renderedTemplate = eta.render("index", { title: "Hello", place: "there!" }) // create `index.eta` in the `views` folder + res.status(200).send(renderedTemplate) }) -app.listen(port, () => { - console.log(`Example app listening on port ${port}`) +app.listen(3000, () => { + console.log("Server listening on port 3000") }) ``` + +### Alternatively, define an Express app engine using ETA + +Missing the good'old `res.render` to render computed templates ? Here is a quick walk around to achieve the same behaviour throughout the whole application. + +Note : `app.engine("eta", eta.render)` is no longer supported on `v3.x.x` for Node.js and Deno + + +```js +const express = require("express") +const path = require("node:path") +const { Eta } = require("eta") + +// Create app +const app = express() + +// Setup eta +const eta = new Eta({ views: path.join(__dirname, "views") }) +app.engine("eta", buildEtaEngine()) +app.set("view engine", "eta") + +// Home route +app.get("/", (req, res) => { + res.render("home", { message: "Hello world !" }) // create `home.eta` in the `views` folder +}); + +// Start server +app.listen(3000, () => { + console.log("Server listening on port 3000") +}); + + +function buildEtaEngine() { + return (path, opts, callback) => { + try { + const fileContent = eta.readFile(path); + const renderedTemplate = eta.renderString(fileContent, opts); + callback(null, renderedTemplate); + } catch (error) { + callback(error); + }; + }; +} +```