I am using html views.
Is there a something like this? :
{{include head.html}}
index
</body>
</html>
What you are looking for is a templating engine, since you mentioned the {{ }}tags I am assuming you are using Hogan.js aka moustache(the javascript version).
The documentation can be found here and what you are specifically looking for is the partials section.
Please note, the default express app(if you select hogan) comes installed with the hjs module which does not support partials, you will need to install the hogan-express module and replace them.
A partial looks like so:
{{> head}}
index
</body>
</html>
Partials are sent from a get or post object like so:
res.render('index.html', {
partials: {
head: 'partials/head.html'
}
});
You are looking for a template engine for nodejs?
For example check here: http://node-modules.com/search?q=template+engine
I found the solution.
server.js
var hbs = require('hbs');
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
hbs.registerPartials(__dirname + '/views/'); <-------- include folder
index.html
Index.html includes head.html like this:
{{> head}}
index
</body>
</html>
If you do not want to use ejs or jade etc then you could do it with jquery. Put this code in index.html
<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>
Related
I use hbs to render my pages with partials for navigation and footers.
router.get('/test', function (req, res) {
return res.render('test');
});
On one page I have template that uses mustache.js. This template doesn't work as it should as the {{}} seems to be picked up on the hbs render. Below is a basic example that illustrates the error. If I load this as a static page with express I get "Joe is a Web Developer", if I render it with hbs I get "is a".
Are there any work arounds that wont involve me changing how all my pages are rendered?
<!doctype html>
<html lang="en">
<head>
<title>Mustache.js Inline Method</title>
<script type="text/javascript" src="js/libs/mustache.js" ></script>
<script>
var view = {
name : "Joe",
occupation : "Web Developer"
};
function loadtemp(){
var output = Mustache.render("{{name}} is a {{occupation}}", view);
document.getElementById('person').innerHTML = output;
}
</script>
</head>
<body onload="loadtemp()" >
<p id="person"></p>
</body>
</html>
It was simple enough. I just had to escape the brackets with a \
So all it took was
\{{name}}
Hi I am trying to create dynamic template system in express, where I will get dynamic content from database and then render output in single index.ejs file.
Here is my index.js
router.get('/', function(req, res, next) {
var dataFrmDB = {
pageContent: "<%= data.pageTitle %>",
pageTitle: "home"
};
res.render('index', {data:dataFrmDB} );
});
And index.ejs contains:
<%= data.pageContent %>
What I should do so that I can render "home" as output. Is this possible?
I was working on something similar when we migrated from drupal to nodejs, I used ect for rendering instead of jade, its faster and much easier to deal with, However, its much better to use design pattern if you have a big dynamic website
js controller file
model.homepage(function(data)
{
res.render("homepage.ect",data,function(err,html)
{
// Do something before you send the response such as minification, or error handling
res.send(html);
});
});
ECT file
<html xmlns="http://www.w3.org/1999/xhtml" lang="ar" xml:lang="ar">
<head>
<%- #page.title.body %>
<%- #page.headerScript.body %>
<style type="text/css">#homepage-container{min-height:300px;color:#353535;float:right;width:100%}</style>
</head>
<body>
<% include 'upper_bar.ect' %>
<%- #page.headerAd.ads %>
<%- #page.notifications.body %>
<%- #page.autocomplete.body %>
<%- #page.redirect.body %>
<%- #page.navigation.body %>
<%- #page.overlayAd.ads %>
</body>
</html>
why bother so much?
You can easily do this using templatesjs
without any template engine.
let me show you how your work can be done using templatesjs
html file
<html>
<head>
<title> <%title%> </title>
</head>
<body>
your content goes here
</body>
</html>
now use templatesjs in you node.js file
var tjs = require("templatsjs");
router.get('/', function(req, res, next) {
var data = fs.readFileSync("./index.html");
tjs.set(data); // invoke templatesjs
var output = tjs.render("title","home");
/* this will replace the <%title%> tag
in the html page with actual title*/
res.write(output);
res.end()
});
i have used fs.readFileSync to keep simplicity of code you can use the asynchronus function if you want (fs.readFile).
a good referrence can be found here
Installation :
$ npm install templatesjs
I have a header.html and a footer.html which I would like to be rendered along with other views. I want to accomplish this using Node+Express.
I tried to render views in the following way but clearly it doesn't work:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.render('header');
res.render('home');
res.render('footer');
});
You have to set a template engine to your project.
You can use Swig for instance, it works very nice and it is well documented.
The example below, shows you how to set it and how you can call partial views from a layout or master page.
Install it by doing npm install swig --save on your project root.
You need to install an additional library called consolidate which acts as interface among different template engine libraries, it is kind of standard in express applications.
npm install consolidate --save
require the library in your main script with
consolidate = require('consolidate');
swig = require('swig');
Configure it as follows:
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views'); // set your view path correctly here
Then you can render a page as:
app.get('/', function (req, res) {
res.render('index', {});
});
(Example taken from Swig's author, Paul Armstrong github page)
Layout.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>{% block title %}{% endblock %} - Example</title>
</head>
<body>
<header>
<h1>{% block title %}{% endblock %}</h1>
{% block header %}{% endblock %}
<nav>
<ul>
<li>Home Page</li>
<li>People</li>
</ul>
</nav>
</header>
<section role="main">
{% block body %}{% endblock %}
</section>
</body>
</html>
Index.html:
{% extends 'layout.html' %}
{% block title %}Home Page{% endblock %}
This way, you can decoupled your views as you need :)
When you are using pug, you can take an advantage of include feature, like #Kangcor suggestion
home.pug
html
head
include ./path/to/header.pug
title= title
body
...
include ./path/to/footer.pug
You can use Handlebars partial views
Here is a well documented library
https://handlebarsjs.com/guide/partials.html#basic-partials
Install hbs
https://handlebarsjs.com/installation/#npm-or-yarn-recommended
npm install handlebars
Configure Handlebars
// import library on the your start js file ie: app.js || index.js
let hbs = require('hbs');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
hbs.registerPartials(__dirname + '/views/partials');
app.set('view engine', 'hbs');
Create your partial views ie: header.hbs and footer.hbs on the partials directory
Create a file layout.hbs and you can call the partial view as follows
<div>
{{> header}}
{{> body}}
{{> footer}}
</div>
Then when calling
res.render("home", {});
home.hbs will be mapped as the body and the footer and header will be added to the layout.
i'm using html files instead of ejs, but the express engine is ejs
views
|
|--header.html
|--footer.html
|
|--index.html
I configured like
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
I render my index template by this:
res.render('index.html', {title: 'test'});
But how can i include header and footer.html in index.html
Similar posts
Node.js express: confuse about ejs template
Existing example which is not working
https://github.com/visionmedia/express/tree/master/examples/ejs
The original method for what you asked would be to use partials. Partials have since been removed, and replaced with the include function of EJS. This is how you would include a file:
<% include header.html %>
<% include footer.html %>
Any locals you pass to the rendered page will also be passed to an include. For example:
app.js
app.get('/', function(req, res) {
res.render(__dirname + '/index.html', {
string: 'random_value',
other: 'value'
});
});
index.html
<!DOCTYPE html>
<body>
<%= other %>
<% include content.html %>
</body>
content.html
<pre><%= string %></pre>
The resultant HTML you would get is:
<!DOCTYPE html>
<body>
value
<pre>random_value</pre>
</body>
When using Express for Node.js, I noticed that it outputs the HTML code without any newline characters or tabs. Though it may be more efficient to download, it's not very readable during development.
How can I get Express to output nicely formatted HTML?
In your main app.js or what is in it's place:
Express 4.x
if (app.get('env') === 'development') {
app.locals.pretty = true;
}
Express 3.x
app.configure('development', function(){
app.use(express.errorHandler());
app.locals.pretty = true;
});
Express 2.x
app.configure('development', function(){
app.use(express.errorHandler());
app.set('view options', { pretty: true });
});
I put the pretty print in development because you'll want more efficiency with the 'ugly' in production. Make sure to set environment variable NODE_ENV=production when you're deploying in production. This can be done with an sh script you use in the 'script' field of package.json and executed to start.
Express 3 changed this because:
The "view options" setting is no longer necessary, app.locals are the local variables merged with res.render()'s, so [app.locals.pretty = true is the same as passing res.render(view, { pretty: true }).
To "pretty-format" html output in Jade/Express:
app.set('view options', { pretty: true });
There is a "pretty" option in Jade itself:
var jade = require("jade");
var jade_string = [
"!!! 5",
"html",
" body",
" #foo I am a foo div!"
].join("\n");
var fn = jade.compile(jade_string, { pretty: true });
console.log( fn() );
...gets you this:
<!DOCTYPE html>
<html>
<body>
<div id="foo">I am a foo div!
</div>
</body>
</html>
I doesn't seem to be very sophisticated but for what I'm after -- the
ability to actually debug the HTML my views produce -- it's just fine.
In express 4.x, add this to your app.js:
if (app.get('env') === 'development') {
app.locals.pretty = true;
}
If you are using the console to compile, then you can use something like this:
$ jade views/ --out html --pretty
In express 4.x, add this to your app.js:
app.locals.pretty = app.get('env') === 'development';
Do you really need nicely formatted html? Even if you try to output something that looks nice in one editor, it can look weird in another. Granted, I don't know what you need the html for, but I'd try using the chrome development tools or firebug for Firefox. Those tools give you a good view of the DOM instead of the html.
If you really-really need nicely formatted html then try using EJS instead of jade. That would mean you'd have to format the html yourself though.
you can use tidy
take for example this jade file:
foo.jade
h1 MyTitle
p
a(class='button', href='/users/') show users
table
thead
tr
th Name
th Email
tbody
- var items = [{name:'Foo',email:'foo#bar'}, {name:'Bar',email:'bar#bar'}]
- each item in items
tr
td= item.name
td= item.email
now you can process it with node testjade.js foo.jade > output.html:
testjade.js
var jade = require('jade');
var jadeFile = process.argv[2];
jade.renderFile(__dirname + '/' + jadeFile, options, function(err, html){
console.log(html);
});
will give you s.th. like:
output.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><title>My Title</title><link rel="stylesheet" href="/stylesheets/style.css"/><script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script></head><body><div id="main"><div ><h1>MyTitle</h1><p>show users</p><table><thead><tr><th>Name</th><th>Email</th></tr></thead><tbody><tr><td>Foo</td><td>foo#bar</td></tr><tr><td>Bar</td><td>bar#bar</td></tr></tbody></table></div></div></body></html
then running it through tidy with tidy -m output.html will result in:
output.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Linux (vers 25 March 2009), see www.w3.org" />
<title>My Title</title>
<link rel="stylesheet" href="/stylesheets/style.css" type=
"text/css" />
<script type="text/javascript" src="../js/jquery-1.4.4.min.js">
</script>
</head>
<body>
<div id="main">
<div>
<h1>MyTitle</h1>
<p>show users</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td>foo#bar</td>
</tr>
<tr>
<td>Bar</td>
<td>bar#bar</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
building off of oliver's suggestion, heres a quick and dirty way to view beautified html
1) download tidy
2) add this to your .bashrc
function tidyme() {
curl $1 | tidy -indent -quiet -output tidy.html ; open -a 'google chrome' tidy.html
}
3) run
$ tidyme localhost:3000/path
the open command only works on macs. hope that helps!