Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static files in Express with mustache templating

I'm trying to serve a folder of static mustache files from Express, but can't seem to figure out how to get it working. Say I just have an object of data like

{
  a: 'Hello :)'
  b: 'Goodbye :('
}

And two files,

public/a.html

<div>{{a}}</div>

public/b.html

<div>{{b}}</div>

How could I get express setup to where it serves any arbitrary number of static html files and replaces the templated parts with just my one big object? Thanks!

like image 583
Weston Avatar asked Jun 18 '16 20:06

Weston


People also ask

Can Express serve static files?

Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.

What are static template files in Express?

A template engine enables you to use static template files in your application. At runtime, 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.

How do I serve a static file in node JS?

In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.

Which is the best template engine for Express?

There are a number of template engines available today, and the more popular ones include Pug (fka Jade), Handlebars, EJS, Mustache, Swig, and others. This post will discuss the following template engines for Express: Pug. EJS.


3 Answers

Static files are usually only called static when they are not processed in any way before sending to user.

What you're trying to achieve is a typical templating system. You can just follow instructions in the plugin:

var mustacheExpress = require('mustache-express');

// Register '.html' extension with The Mustache Express
app.engine('html', mustacheExpress());

app.set('view engine', 'mustache');
app.set('views', __dirname + '/views'); // you can change '/views' to '/public',
    // but I recommend moving your templates to a directory
    // with no outside access for security reasons

app.get('/', function (req, res) {
    res.render('a');
});

Also consider using Handlebars, it's often more convenient to use than Mustache. You can find a list of differences in this question.

like image 105
zlumer Avatar answered Oct 11 '22 21:10

zlumer


You can use mustachejs just like pug in express by setting mustache as view engine and defining its working like below code:

//required files
const fs = require("fs")
const mustache = require("mustache")

// To set functioning of mustachejs view engine
app.engine('html', function (filePath, options, callback) { 
    fs.readFile(filePath, function (err, content) {
        if(err)
            return callback(err)        
        var rendered = mustache.to_html(content.toString(),options);
        return callback(null, rendered)
    });
  });

// Setting mustachejs as view engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine','html');

//rendering example for response
app.get('/',(req,res)=>{        
    res.render('index',{data:'Sample Data'});
});
like image 22
Aditya Vashishtha Avatar answered Oct 11 '22 23:10

Aditya Vashishtha


I modify zlumer's answer a little bit and the following code works fine for me.

const express = require('express');
const app = express();
const mustacheExpress = require('mustache-express');

app.engine('html', mustacheExpress());

app.set('view engine', 'html');
app.set('views', __dirname + '/views');

app.get('/', function(req, res) {
  const data = {
    hello: 'world',
    foo: 'bar'
  };

  res.render('test', data);
});

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

Please check https://github.com/HemingwayLee/sample-mustache-express and feel free to clone and modify it.

like image 34
Kenny Lee Avatar answered Oct 11 '22 23:10

Kenny Lee