Serving static files in Express with mustache templating

16,045

Solution 1

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.

Solution 2

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'});
});

Solution 3

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.

Share:
16,045
Weston
Author by

Weston

Updated on June 16, 2022

Comments

  • Weston
    Weston almost 2 years

    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!

  • Weston
    Weston almost 8 years
    Yeah I had noticed that plugin when googling earlier, but since there's no documentation I was really confused. What exactly is the 'a' in res.render('a')? I'd like to be able to have an arbitrary number of files in /views and have them all rendered using the same data object.
  • zlumer
    zlumer almost 8 years
    The 'a' in res.render('a') is the name of your template: a.html (without extension). You can pass the same data object to every render() call like that: var data = {a:1,b:2}; res.render('a', data);
  • Weston
    Weston almost 8 years
    So how would I also incorporate b into this setup?
  • zlumer
    zlumer almost 8 years
    res.render('b', data); — the templates are loaded automatically if they are in the /views directory with .html extension (as configured with the code above)
  • Levi Roberts
    Levi Roberts almost 8 years
    Maybe things have changed since you posted your comment "there's no documentation". What documentation are you looking for exactly? I followed the Handlebars Github project link in this answer and found fairly verbose and complete documentation. Maybe give Handlebars another try as it really does abstract away the complexities that Mustache introduces.
  • Adrian Moisa
    Adrian Moisa over 7 years
    Thank you for this simple answer!
  • binki
    binki about 7 years
    If you use app.engine('html', …) then you have to do app.set('view engine', 'html').