Dogan
Dogan

Reputation: 13

How to make .js variables accessible to .ejs files

I have an index.js file and a list.ejs file, which i told the express file to include:

index.js:

const express = require("express");
const app = express();

app.set("view engine", "ejs"); //Express Template Engine = embedded js
app.set("views", __dirname + "\\views");

let varToUseInEJS = 5;

app.get("/", (req, res) => {
    console.log("Path of Request: " + req.path);
    res.render("list");
});

app.listen(8080, "localhost", 1, () => {
    console.log("Example app listening on: 127.0.0.1:8080");
})

list.ejs:

<!DOCTYPE html>
<html>

<body>
    <table>
        <tr>
            <th>Number</th>
        </tr>
        <% for(let i = 1; i < varToUseInEJS; i++) { %>
            <tr>
                <td>
                    <%= i %>
                </td>
            </tr>
            <% } %>
    </table>
</body>

</html>

when i change the "varToUseInEJS" to for example 5, it works and shows a table with 1 to 5 + header, but in this case, node.js debugger gives me the following error:

>> 9|         <% for(let i = 1; i < varToUseInEJS; i++) { %>
10|             <tr>
11|                 <td>
12|                     <%= i %>
varToUseInEJS is not defined

is there any way to make all .js files' variables automatically visible to ejs files?

thanks in advance for any help.

Upvotes: 1

Views: 3254

Answers (3)

Mahan Mashoof
Mahan Mashoof

Reputation: 169

the key varToUseInEJS refers to the .ejs file ... and ... the value varToUseInEJS refers to the .js file

app.get('/', (req, res) => {
    res.render('list', {varToUseInEJS: varToUseInEJS});
}

Upvotes: 1

Francisco
Francisco

Reputation: 2228

This will pass in varToUse to the sheet. Note the second parameter is just a JS object.

app.get('/', (req, res) => {
    res.render('list', {'varToUse': 5});
}

Upvotes: 0

khalito
khalito

Reputation: 1149

To generalise on @Francisco, you could also pass in varToUseInEJS as a variable. Just make sure that the name of the variable that you pass in res.render() matches the names in your EJS expressions.

`app.get('/', (req, res) => {
    res.render('list', {'varToUseInEJS': varToUseInEJS});
}`

Upvotes: 0

Related Questions