Lukon
Lukon

Reputation: 265

How to pass function required from another .js file into an index.ejs view via app.js

graphs.js: contains a function that makes an API call and returns an object with an HTML link that will be used to embed a graph.

app.js: contains the following (graphs.js has been required):

var express = require("express");
var app = express();
var graphs = require("graphs"); <---

app.use(express.static(__dirname + '/'));
app.set("view engine", "ejs");

app.get("/", function(req, res){
    res.render("index");
    CAN I PASS THE FUNCTION THROUGH HERE?
});

//server
app.listen(process.env.PORT, process.env.IP, function(){
    console.log("Dev server started!");
});

index.ejs: I am attempting to pass the graphs.graph API function call through app.js so it is usable and executed in my index.ejs

For example:

<div class="graph-test">
    <% graphs.graph() %>
</div>

Any advice, best practice comments, or any other methods of doing this would be greatly appreciated. Thank you!

Upvotes: 0

Views: 153

Answers (1)

Tolsee
Tolsee

Reputation: 1705

No, you wouldnot send a function through res.render(). The practice is you deal which your logic/process in your route or controller first and then send only computed data into to template engine. It might be confusing some time as you can also write js in your template engine, but template engine only replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. Like below:

app.get("/", function(req, res){
   var data = graphs.graph();
   res.render("index", {data: data});
});

And talking about your specific problem, If your API call is done from server-side, then you should do like above. If your API call should be done through client-side then you can embed the js file into your view.

Upvotes: 2

Related Questions