How to pass data from Node server to ejs header - node.js

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!

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

How to render express views dynamically

I'm new to express JS and try to build CMS like this:
Users have a page builder, where they can drag-and-drop different components on the page.
each component has its own data which also is defined by a user
Each component has its own view template
So, I have to check what components have to load, prepare data for each of them, send this data to an appropriate template, render one big HTML and send to the client.
I know, It's too complicated to explain how to build this, but any tutorials, examples, resources would be appreciated.
IIUC, you can accomplish this using the include function that most template languages have. For the example, I'll use ejs. Also, I'm assuming you know how to get the data for user selections to your server.
on your app.js:
app.get('/someRoute', function(req, res) {
var data = //get user data here
res.render('someTemplate', {data:data});
});
someTemplate.ejs:
<%- include('header') %> //you should do this on every page
<% if (data == 'foo') { %>
<%- include('foo', {data:data}) %> //note that you can pass data to templates like this
<% } %>
<% if (data == 'bar') %>
<%- include('bar') %>
<% } %>
<% include('footer') %>
foo.ejs:
//some component here
If you want to read more, check the docs.
Hope this helps!
You can use Template Engine for that purpose because it enables you to use static template files in your application. At run time, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
Some popular template engines that work with Express are Pug, Mustache, and EJS. The Express application generator uses Jade as its default, but it also supports several others.
Also check this link

express-handlebars accessing variables declared in the client javascript

I am learning to use handlebars for templates in my website.
I am using node.js so I have used the express-handlebars module as it seems popular and has a lot of support.
I set up some basic config as so..
var exphbs = require('express-handlebars');
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({
defaultLayout: 'layout',
}));
app.set('view engine', 'handlebars');
My understanding is that my views in handlebars (ie my content pages) are templates in handlebars and under the hood I think these templates are being compiled on my behalf so that I can concentrate on using them.
Now, I can pass in data to the template from my node express router and then access and render data in the template using the handlebars notation {{ variable }}.
That's great. But....I want to declare variables on the client using javascript, probably as the result of getting some data back from an Ajax call that I want to enter. Unfortunately this never seems to work. I cannot figure out how I can access a local variable in my template. There is surely a way to do it?
the #with block helper looked promising but unfortunately it didn't do what I expected.
Here is a snippet of one of my content pages with a couple of attempts to declare data locally and render its value.
<div>
<script>let test = {
text: 'this is my example text'
};
</script>
<div>
{{#with test}}
{{text}}
{{/with}}
</div>
<div>
{{test.text}}
</div>
</div>
I have read a lot of articles and watched a lot of videos and I just cannot find anywhere where somebody uses the 'express-handlebars' module and then renders data defined locally.
I am probably missing something obvious but I have been struggling for a while now.
Does anybody have any idea how I can do this please?
thanks in advance.
Okay...it looks like client-side templateing has to be configured separately using webpack. I suppose this makes sense because express handlebars compiles the templates (which just resolves to plain javascript that takes the variables I want to render and wraps in the html needed) and I haven't been able to find any templates on my client through the inspector in the browser. I haven't had chance to try it yet, but this looks promising : http://initialdigital.com/sharing-handlebars-templates-on-both-server-client-in-node-js-express-with-webpack/

How to get username injected into html?

I have a static html site:
index.html
I want to use handlebars {{username}} to inject a username variable. It looks like:
res.render('index', {username:'MyName'})
should work. The problem is my index.html is in my '/static' (my express.static()) directory. What is the best way to get my username variable into my html page without having to convert it to something that doesn't look like html? Thats why I dont want to use jade and prefer handlebars. If there is some other way, it would be best.
Update: I would like to preserve the same structure I have (keeping everything in my static directory) as opposed to moving things out to a "views" directory. Is this possible?
Then you must have to use Template engine. You can use Jade it also support HTML, only you have to use . at end of tag like:
doctype 5
html. // THAT DOT
<body>
<div>This is jade testing with HTML</div>
</body>
Is there a way to keep the file in my /static directory without having
to put it in the "views" directory?
Yes you can use _dirname while rendering
app.get('/anyurl/' , function(req, res){
res.render(__dirname + '/../static/path/folder') //modify path according to your structure
});

How can I use Express to render dynamic files?

I'm looking to use Express to render raw strings as HTML, with the ability to reference static files in a specified directory (CSS, images, and other resources).
I've done a lot of research, but I haven't seen anything that approaches what I'm trying to do. For example, I thought perhaps writing a custom templating engine that only pretended to load a file would cut it, but that doesn't seem to do the trick.
What's the best way to approach this?
There are many ways to do it.
It can done in any other templating engine as well but here i am guiding you to implement same using EJS(Embedded Javascript).
Use Express Generator to create an ExpressJS app with EJS templating Engine.
command :
express --ejs AppName
For more information about express Generator refer to doc here
Now EJS has tags such as :
1. <% code %> - Code that is evaulated without "echo" it is not printed out.
2. <%= code %> - Code that is evaluated and printed out and escaped!
3. <%- Code %> - Code that is evaluated printed out and not escaped!
So in your case you can use 3rd the third tag that i have mentioned above.
Render EJS views in the usual way from your route config:
res.render('index.ejs', {
// data you want to pass ..
});
Code sample
Some time ago i was playing around with EJS, i developed a very small blogApp for practice.
You can look into this view, line number 33, for more practical way of implementing same.

How to include html code in a view?

I'm using express.js and EJS as template engine.
I don't understand how to use partials, I have seen at the examples but the author used JADE template engine, so I don't know how to apply it with EJS.
I have a simple view named: test.ejs and another .ejs file named part1.ejs
I need to show part1.ejs inside test.ejs.
I tried putting <% partial('part1', {}) %> (into test.ejs) but nothing happen, It does not include that file.
Could someone give me an example?
Thank you!
The correct code in your situation would be:
<%- partial('part1') %>
If you want to include unescaped HTML use <%- and if you want to escape HTML (unlinkely though when including a partial) you can use <%=.
Resources:
Node.js - EJS - including a partial
http://groups.google.com/group/express-js/browse_thread/thread/62d02af36c83b1cf
Its an old thread, but here is how you do it in the newer version of EJS.
<% include part1 %>
given part1.ejs contains the html you wish to include.

Resources