Migrate from static HTML to template engine

Issue

Having tied myself up in knots trying to expand my static pages to be more ‘dynamic’, I am now thinking that it’s time to try some server side templating (no experience in this area). I would like to migrate across slowly rather than make large changes in one go.

If I am using nodejs, express and a template engine (e.g. ejs), can I use my existing html (which runs JS to get data from a parse-server and display) as the starting point? So, as a simple example, using my existing HTML as is, can I pass in a variable before serving the page? Then let the client side JS run as it did previously but now use the earlier passed variable?

Would I need to deconstruct the HTML into something that is compatible with a given template engine (e.g. change how the JS and CSS files are referenced)?

The info I find online shows creating the template from scratch rather than using an existing HTML file; so not clear if this is possible.

Solution

Yes, it should definitely be possible to begin using a templating engine and using variables in your HTML without needing to rewrite the entire frontend structure. With ejs, you need to rename all of your HTML files that will be using variables with the file extension .ejs, but you’re then immediately able to use all the ejs syntax to do stuff like render variables, all in normal HTML code.

Here’s some code that works as a pure HTML file:

<!DOCTYPE html>
<html>
    <head>
        <title>My Website</title>
    </head>

    <body>
        <h3>This file works as pure HTML or with a templating engine! It just depends on the file extension.</h3>
        <p>A normal paragraph.</p>
    </body>
</html>

Now here’s the exact same code, but with the .ejs file extension and it uses a variable from the server:

<!DOCTYPE html>
<html>
    <head>
        <title>My Website</title>
    </head>

    <body>
        <h1>This file works as pure HTML or with a templating engine! It just depends on the file extension.</h1>
        <p>A normal paragraph.</p>
        <p>Here's the content of a variable passed from the server: <%= myVar%></p>
    </body>
</html>

The last paragraph is rendered as Here's the content of a variable passed from the server: foo bar

And in your express backend, to pass variables to a file, just put them in an object after the name of the file you are rendering:

app.get("/", (req, res) => {
    res.render("home", {
        myVar: "foo bar",
        anotherVar: "hello world",
        // etc
    });
});

Answered By – isaac.g

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published