How to complie dynamic html using cons.underscore? - node.js

I have converted static html and converted it into strings and emailed it. Now want to pass dynamic value to the html and convert it into string and email it. I'm using cons.underscore as view engine for rendering html pages.

DON'T USE readFileSync! It will lock your program!
If you need pass dynamic variables into template render, you need use the .render in your express server.
Maybe you will need install the extensions:
npm install underscore --save
npm install consolidate --save
For this, set your template engine in express:
app.set('view engine', 'html');
app.engine('html', require('consolidate').underscore);
And get the page like this on your listener:
var options = { email : 'test#op.com'};
res.render('index', options);

Related

pug.compile() cannot find template files (res.render() can)

I'm writing a small NodeJS/Express app. I set up pug as its template engine:
const app = express();
app.set('view engine', 'pug');
app.set('views', __dirname + "/public/views");
app.use(express.static(__dirname + '/public/static'));
This works fine when calling a res.render() to send HTML responses:
app.get('/', function getIndex(req, res){
res.render('index.pug');
});
But when I try to render small components and collect them in a string or an array as response to an AJAX call, I can't get it to work.
const pug = require('pug');
const compile = pug.compileFile('option.pug');
This always results in Error: ENOENT: no such file or directory, open 'option.pug'. I tried changing the path to the router's perspective (so something like ../../public/views/option.pug) but this also does not help.
I don't know why the paths are interpreted differently.
How do I refer to this template when using pug.compileFile?
From the Pug source code, the passed path is set as the filename in the options:
https://github.com/pugjs/pug/blob/926f7c720112cac76cfedb003e25e9f43d3a1767/packages/pug/lib/index.js#L354
This is then passed to handleTemplateCache to read the file:
https://github.com/pugjs/pug/blob/926f7c720112cac76cfedb003e25e9f43d3a1767/packages/pug/lib/index.js#L215
So ultimately the path is just being passed to fs.readFileSync, which treats relative paths as being relative to the current working directory, process.cwd().
You could generate the appropriate path using something like this:
const file = app.get('views') + '/option.pug';
It would be better to use path.join rather than string concatenation for building paths, https://nodejs.org/api/path.html#path_path_join_paths
const path = require('path');
const file = path.join(app.get('views'), 'option.pug');
If you don't want to (or can't) use app.get('views') you could just build up the absolute path by other means, such as using __dirname directly.
Note also that you can pass a callback to res.render which will be passed the rendered HTML instead of writing it to the response. That may allow you to avoid calling the template directly in the first place.

using parameters in url causing included files to be downloaded from same url

I want to get parameters from url and display content based on the parameters.
I am using express 4 here is my code
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/showcontent/:book/:page',
function(req, res) {
console.log("app.get parameters");
res.render('bookPage', { book: req.params.book,page: req.params.page });
}
);
in my public folder there are css and js files. when i use url with parameters like
mydomain.com/showcontent/book/page123
it tries to get css and js files from
mydomain.com/showcontent/book/page123/css/style.css
mydomain.com/showcontent/book/page123/js/script.js
while it should get the files from public folder from url
mydomain.com/css/style.css
mydomain.com/js/script.js
everything works fine if I use url format like this
/showcontent?book=1234&page=12345
but i dont want to use this format, I think some thing is missing in my code please someone help me solve to get parameters from url using forward slash format and still get css and js files from public directory

Express + Consolidate + Hogan: ` Error: cannot find module 'hogan' ` with code straight from consolidate docs

I'm getting an Error: cannot find module 'hogan' when I send a request to the node.js server implemented in Coffeescript here:
https://gist.github.com/wmayner/306c89d7f8fbeed3f098
I've installed the dependencies hogan.js, consolidate, and express.
I've reproduced the example code from consolidate's documentation (reproduced below) almost exactly, so I'm having trouble seeing where this error is coming from. It looks like it should work.
From the consolidate docs:
var express = require('express')
, cons = require('consolidate')
, app = express();
// assign the swig engine to .html files
app.engine('html', cons.swig);
// set .html as the default extension
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
I've also tried declaring `hogan = require('hogan.js')' as a dependency.
Anyone have an idea why this is happening?
Note: The gist above differs from the consolidate docs in that I'm setting the view engine to hogan rather than html. This is because I'd rather use .hogan than .html for my template file extensions (I've tried .html and I get the same error).
Your gist sets hogan as view engine, but that should be html like in the Consolidate docs:
// tell Express to use Consolidates 'hogan' renderer for .html templates
engines = require 'consolidate'
engine = 'hogan'
app.engine 'html', engines[engine]
// tell Express to use '.html' as extension to find views with .render()
app.set 'view engine', 'html'
EDIT: realizing that perhaps you want to use .hogan as extension for your template files, you could use this instead:
app.engine 'hogan', engines[engine]
app.set 'view engine', 'hogan'

using dustjs-linkedin templates in node.js and express3.x

I can't figure out how to use the dustjs-linkedin templates for express 3.x
#app.js
var dust = require('dustjs-linkedin');
app.set('view engine', 'dust');
app.get('/test1', routes.test1);
#./routes/test.js
exports.test1 = function(req, res){
res.locals.session = req.session;
res.render('test1', { title: 'Test 1' } );
};
#./views/test1.dust
{+base.dust/}
{<main}
Child Content
{/main}
#./views/base.dust
{+main}
Base Content
{/main}
I get the following error when going to /test1
500 Error: Cannot find module 'dust'
I had the same problems as you. And to ease the use of dustjs-linkedin together with express 3.x i put together the small library klei-dust. The library is simple to setup and you can set the root folder for views, which applies to base-templates and partials.
So if you have a views folder at views/ with home.dust and base.dust templates, the home.dust can look like this:
{>base/}
{<main}
Hello world
{/main}
So there's no need to write views/base.dust for it to work.
I've managed to get a working version of dustjs-linkedin with consolidate module.
https://github.com/chovy/express-template-demo
FYI, the layout has to be double quoted...that was a major gotcha for me, and its relative to app.js file, and it needs a trailing /
{+"views/base.dust"/}
<p>Page content here</p>
I will explain u how you should use express 3.x with dustjs-linkedin.
1) express has 2 config to set. 'view engine' and app.engine
"view engine" just sets the default and that app.engine just maps what engine to use for a given file extension.
so you should do something like this:
app.set('view engine', 'dustjs-linkedin');
app.set('views', __dirname + '/views');
app.engine('dust', dust.compileFromPath);
There is only one problem with this is that the method compileFromPath doesn't exist in dust :p.
You should add a method in the dust object with this signature that Express expects: (path, options, callback)
you can read more about this here: http://expressjs.com/api.html#app.engine.
Another option would be to use consolidate (http://spalatnik.com/blog/?p=54) but unfortunately Consolidate doesn't support the dustjs-linkedin version it only support the old dust version.

Mustache(-like) template engine for Express?

Is there a template engine for Express (node.js) which is based on Mustache or uses a similar syntax?
All I could find is haml, jade, ejs, jquery templates and one based on CoffeeScript (I write plain JS).
I want to write "normal" html, so only ejs and jqtpl would fit. I already use mustache with backbone so it would be best to also use it on the server side with Node.js
Just stumbled on this ancient thread but no one has mentioned consolidate.js, which seems to be the "right" way under Express 3 (refer to http://expressjs.com/faq.html). It also provides an easy way to switch/experiment with templating systems.
Here's a simple example - http://invitingthebell.com/2012/12/24/mustache-templates-in-express-3-0/.
Code, in case it disappears is:
var express = require('express')
, cons = require('consolidate')
, app = express();
// assign the mustache engine to .html files
app.engine('html', cons.mustache);
// set .html as the default extension
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
// test mustache
app.get('/', function(req, res){
var viewdata = { 'test' : 'Hey now.'};
res.render('index', viewdata);
});
app.listen(3000);
The index.html file in the views directory:
<html>
<head><title>Some CMS</title></head>
<body>
<h1>Mustache</h1>
<p>What do you say?</p>
<p>{{test}}</p>
</body>
</html>
You could probably add Mustache as a rendering engine by following the Express manual:
View filenames take the form “.”, where is the name of the module >that will be required. For example the view layout.ejs will tell the view system to >require(‘ejs’), the module being loaded must export the method exports.compile(str, >options), and return a Function to comply with Express.
Edit:
From the Mustache manual under Usage:
Below is quick example how to use mustache.js:
var view = {
title: "Joe",
calc: function () {
return 2 + 4;
}
};
var output = Mustache.render("{{title}} spends {{calc}}", view);
In this example, the Mustache.render function takes two parameters: 1) the mustache >template and 2) a view object that contains the data and code needed to render the >template.
From the above I suspect you could just export Mustache.render, but I haven't tested it. The object literals used as data look the same, but if they do happen to be different, you could probably just wrap Mustache.render in a function that formats it correctly.
Edit: Xomby's wrapper link contains an example of how to wrap handlebars for express, Mustache should be similar.
Try Hogan.js http://twitter.github.com/hogan.js/
I think it's what Twitter and LinkedIn uses in production.
Here's a working example/tutorial on using NodeJS, ExpressJS and MustacheJS Template Engine:
http://devcrapshoot.com/javascript/nodejs-expressjs-and-mustachejs-template-engine
You can build out a complete web page like you normally would, placing the mustacheJS fields where you like. Use express to route to the page, use node fs.readFileSync(); to get the html file, use mustache to update the data on the page then spit it out to the client.
It's kinda neat. I hope it helps!
-A-
Have you already tried stache ? It is no longer maintained but you can follow some links and get more recent stuff ..
I found Handlebars.js which is an extension of the Mustache template system/language.
And there is a really simple wrapper to use it with Express.
Sure, the best way to do this is the post here:
http://iamtherockstar.com/blog/2011/11/21/using-mustache-templates-express-apps/
So far, this has worked great for me. The only problem I have found is not using partials at the root path for views. For example partials in view/partials - the engine by default only finds partials as view. Let me know if you figure that out!
Check out Handlerbars. " Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.
Handlebars is largely compatible with Mustache templates. In most cases it is possible to swap out Mustache with Handlebars and continue using your current templates. Complete details can be found here " - Handlebars

Resources