How can express and jade does not compress html? - node.js

I using express and jade, but when I debug I doesn't want jade compress my html, are there any way to pass an option jade globally and make it does not compress html.

If you use Express 3.x, you can control compression via app.locals.pretty. I usually enable it while development:
app.configure('development', function () {
app.locals.pretty = true;
});

In the time since this answer was written an option has been added to control this behaviour.
app.locals.pretty = true;
At the moment, no. This feature has been discussed here:
https://github.com/visionmedia/jade/pull/205
The html doesn't actually get compressed or minified by default, though. It's just not formatted nicely. The simplest way I've found to make it human-readable is to use Chrome's dev tools, which give you a nice foldable representation of the source.

You can use Jade Comments to annotate your code for viewing in the browser.
//h1
h1 Some Title
//p
p some content
will output
<!--h1-->
<h1>Some Title</h1>
<!--p-->
<p>some content</p>
The template is already compiled once it leaves the server, so if you wanted to view the template in the browser you would have to write a plugin that de-compiles html to jade and than display the decompiled version.

Huh, new to nodejs so maybe missing something here; but in app.js adding app.set('view options', {pretty: true}); was ineffectual (using express 3.0.3).
..doesn't appear to be supported? did find a workaround, e.g. on a per route basis:
exports.index = function(req, res){
res.render('index', {
[... other stuff ...]
pretty: true
});
};

For whom using pug-cli, you need to add --pretty in cmd(terminal). Like the following,
pug --pretty -w -o dist/html/ assets/pug/index.pug

Related

node.js/Jade - How to pre-compile jade files and cache it?

Framework: node.js / express.js / Jade
Question: in production env, when a jade file is rendered by express, jade cache's it so future renders are faster.
When I start node.js app, how can I pre-compile (or) pre-render (like warmup) all the jade files so its already in cache when requests start to come in...
I can use a folder recursion, I just need to know how to pre-compile (or) pre-render.
Is this possible?
Jade has template pre-compiling and caching built in.
http://jade-lang.com/api/
Simply specify cache: true option to jade.compileFile, and iterate through all of your template files.
var options = {cache: true};
// iterate/recurse over your jade template files and compile them
jade.compileFile('./templates/foo.jade', options);
// Jade will load the compiled templates from cache (the file path is the key)
jade.renderFile('./templates/foo.jade');
If you're not using any parameters, you can compile jade templates directly to HTML with grunt or gulp and make it watch for file modifications
Try it from the command-line:
jade view/map-beacons.jade -D
If you do need to use parameters I would use something like in Andrew Lavers answer.
compileFile returns a function which you can use to pass in parameters i.e. fn({ myJsVar: 'someValue' })
There is also a client option in the command-line but I didn't find any use for it :
jade view/map-beacons.jade -cD
i do this solution, this code outside http.createServer function
let cache_index=jade.renderFile('index.jade');
and when return view
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(cache_index);
when use this solution server return index to 1ms
but without solution server return index between 150ms to 400ms
result:
Picture 1 with cache
Picture 2 without cache

Get return value of `include` in jade template

What I basically try to accomplish is to re-use jade partials/templates when getting data through a socket connection. Non working example:
socket.on('company_created', function(company) {
var html = include _company;
$('#companies ul').append(html);
});
Normally I had to create a new li and set the content like so (which is working as expected):
$('#companies ul').append($('<li>').text(company.name));
This is okay for a simple list, but if I had complexer list and stuff, this could get messy pretty quick, plus I had to write plain HTML again, so I figured re-using my already existing jade templates with all their goodness would be awesome, but had not luck, yet.
Any clue?
PS: Please do not tell my to use Ember, Backbone, Derby, Meteor, Angular or whatsoever.
Thanks in advance!
You can compile your jade sources to JS with jade.compile. Then include these sources in the client-side javascript, include jade's runtime.min.js, and refer to your jade templates as to normal JS functions in your client-side code.
For example,
server.js
app.get('/templates/:template.js', function (req, res) {
var template = req.params.template;
response.end([
"window.templates = window.templates || {};",
"window.templates[\"" + template + "\"] = " + jade.compile(template + ".jade", { client: true; });
].join("\r\n"));
});
client.js
$(function() { $("#placeholder").html(window.templates["content"]({user: "Daniel" })); });
content.jade
h1: Hello #{user}!
index.jade
!!!
html
head
script(src='/lib/jquery/jquery.js')
script(src='/lib/jade/runtime.min.js')
script(src='/templates/content.js')
script(src='/scripts/client.js')
body
#placeholder
Note that the code above might be syntactically incorrect and is provided solely to illustrate the idea.
we have a build step that compiles them to functions sort of like penartur mentioned. I dont use extend or include (which dont work on the client anyway ATM), but personally I find we have absolutely no need for that on the client at all since the DOM provides all the separation we need.

Node.js + Express - How to get Mustache partials working?

I'm trying to get Mustache working properly with Express, and as one can guess, I'm having troubles.
The following line initializes Mustache nice and clean. Variables render as expected.
app.register('html', require(__dirname+'/public/js/libs/mustache.js'));
However, the problems start to rise when partials are thrown in the mix. With Mustache, this here partial should invoke header view/partial.
{{> header}}
But alas, nothing happens. :/ Even when I offer the partial directly, Mustache fails to render it.
app.get('/', function(req, res) {
res.render('welcome', {
partials: {
header: '<h1>Header</h1>'
}
});
});
So, it seems that the partials aren't working at all. I've found one hack that get's the partials somewhat working:
http://bitdrift.com/post/2376383378/using-mustache-templates-in-express
After that the partials render when offered directly at render call (see above), but it still fails on rendering the partials directly to views/layouts:
Layout looks something like this:
Behold, the header
{{> header}}
<p>Let's move to more important stuff...</p>
Header view looks something like this:
<h1>Header</h1>
Express can load the views by themselves just ok, but it doesn't know how to handle the Mustache partials...
Using express (at least version 3) and mustache-express, You can load partials as usual using double mustaches that begin with a greater than sign.
First consider the following is appended within our app.js file:
/** import the module */
import mustache from 'mustache-express';
/** view engine setup */
app.engine('mst', mustache());
app.set('view engine', 'mst');
app.set('views', path.join(__dirname, 'mvc/views'));
/** the route where we will display the partials */
app.get('/', (req, res) => {
let view = {
title: 'Homepage',
// ...
};
/** we are going to use a file called template.mst for rendering */
res.render('template', view);
});
Any double mustaches that begin with a greater than sign (i.e. {{> file}}) will be considered a partial. The file within the partial will be rendered at runtime. Consider this file to be a partial we want to insert:
mvc/views/partial.mst
<h2>418 | I'm a teapot</h2>
And here is our template:
mvc/views/template.mst
<h1>template.mst file</h1>
<!-- output: <h2>418 | I'm a teapot</h2> -->
{{> partial}}
Managed to get this working with the latest version of hogan-express.
https://github.com/vol4ok/hogan-express
All that is needed is to install hogan-express and use it as template engine on express. No hacking or tuning required.
I'm not sure what's exactly in your ./public/js/libs/mustache.js ... I use the mustache module from npm + a variation of the templating object you linked to.
In any case, the object you pass to app.register needs to call mustache.to_html(template, locals, partials) at some point.
You need to pass the partials object as the third argument to mustache's to_html.

How to compile jade templates in to JavaScript functions to use them on client side?

I want to use compiled jade templates on client side. How should I compile them to get javascript files ?
https://github.com/visionmedia/jade
Yes you can! https://github.com/techpines/asset-rack#jadeasset
I just open sourced "asset-rack", a nodejs project that can can precompile jade templates and serve them in the browser as javascript functions.
This means that rendering is blazingly fast, even faster then micro-templates because there is no compilation step in the browser.
First you set it up on the server as follows:
new JadeAsset({
url: '/templates.js',
dirname: __dirname + '/templates'
});
If you template directory looked like this:
templates/
navbar.jade
user.jade
footer.jade
Then all your templates come into the browser under the variable "Templates":
$('body').append(Templates.navbar());
$('body').append(Templates.user({name: 'mike', occupation: 'sailor'});
$('body').append(Templates.footer());
#coffeescript
jade = require 'jade'
data = '#menu'
options =
client: true
compileDebug: false
fn = jade.compile data, options
console.log fn.toString()
Look for proposed solutions in the jade issue 149 discussion. Unfortunately, there is no built-in ready for use option, as I know.
You should probably look at integrating this into a Grunt build task.
See grunt-contrib-jade
Blade is a Jade-like HTML template engine that has a built-in middleware for serving compiled templates to the client. :) Check it out!
This question is a bit dated, but there is a method of compiling Jade templates,
var jade = require('jade');
var fn = jade.compile(jadeTemplate);
var htmlOutput = fn({
maintainer: {
name: 'Forbes Lindesay',
twitter: '#ForbesLindesay',
blog: 'forbeslindesay.co.uk'
}
})
Just got to the tutorial and search for compile, or the API under
jade.compile(source, options)
Be sure to set, compileDebug so you get the source,
Set this to false to disable debugging instrumentation (recommended in production). Set it to true to include the function source in the compiled template for better error messages (sometimes useful in development).

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