How to pass data from Node server to ejs header

Viewed 323

I am trying to create a Node website with a header ejs file that is included on each page.

When I load my index.ejs page, I would also like to pass a variable from my server to my header page.

I could be wrong, but it seems like the best way to do that is to pass that variable from the server, to the index page, then to the header.

Currently, the only example I've seen of this is the following code snippet:

<%- include("header",{title:"your_title"}) %>

The catch is that I would need to replace "your_title" with a title variable that I set serverside.

Is there a way to do this?

My hunch is that it may look like the following:

<% runHeader = function(title){ %>
  <%- include('../partials/header', {title: title}); %>
<%}; %>

Unfortunately, include does not seem to run properly here, and the header does not load at all.

Any help would be much appreciated!

1 Answers

so the best way I found for this to work is to make a a "views" folder under your project folder. The views folder will have an ejs file with the name of "title.ejs" the call should then look like <%- include("title") -%>this will look for the ejs file in the same directory. I'd say in the title file add some sample HTML then everything should work.

Make sure that you have NPM installed ejs, then in nodefile use const ejs = require("ejs"); and app.set('view engine', 'ejs'); and app.use(express.static("public"));in the same node.js file.

Hope this makes sense and good luck.

Related