Reputation: 1988
I'm probably missing something obvious, but I'm new to this workflow. I've got an Express app setup and I'm using Jade as the template engine. I'm trying to use a tool called "gulp-bundle-assets" which bundles all of my scripts into one, and outputs them with a hash in the name (I assume to avoid cache issues). It also includes a JSON file which is supposed to be used to integrate the scripts into your app. It looks like this:
{
"main": {
"styles": "<link href='main-8e6d79da08.css' media='screen' rel='stylesheet' type='text/css'/>",
"scripts": "<script src='main-5f17cd21a6.js' type='text/javascript'></script>"
},
"vendor": {
"scripts": "<script src='vendor-d66b96f539.js' type='text/javascript'></script>",
"styles": "<link href='vendor-23d5c9c6d1.css' media='screen' rel='stylesheet' type='text/css'/>"
}
}
How do I include this data in my Jade template? I saw a utility for compiling Jade templates that does variable interpolation, is that the best way to handle it, or is there something native within Jade?
Upvotes: 3
Views: 686
Reputation: 550
When you use JADE in a NodeJS Express Server, you may need to send data to your views. I think it is you need. Because of your data is JSON format, you need to use the JSON methods to convert into a legible format for your JADE Template view.
Try with the next sample code:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
let port = process.env.PORT || 3030;
var app = express();
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
let jsonFile = require('./public/jsondata.json');
let jsonData = JSON.stringify(jsonFile);
let json = JSON.parse(jsonData);
let mStyles = json.main.styles; //You get your main styles
res.render('index', { mainStyles: mStyles });
}).listen(port, function(){
console.log('Listening on' + port);
});
And your JADE template located in the templates
folder with the next content:
html(lang="en")
head
meta(charset="utf-8")
#{mainStyles}
title Hello World
You are passing a mainStyles
var to the JADE template file.
Don't forget customize your JSON file location.
Upvotes: 1