Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express-ejs-layout using different layout

Im using express-ejs-layout for my project. my project has routing. I want use different layout for different res queries. for example if query is: www.xxx.com/a, use LayoutA.ejs, if query is: www.xxx.com/b, use LayoutB.ejs. My index.js part code is:

...
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/app_server/views'));
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());


app.use(ejsLayout);

app.use('/public', express.static(path.join(__dirname, 'public')));
require('./app_server/routes/routeManager')(app);
...

how can I?

like image 447
eylesa Avatar asked Mar 05 '23 14:03

eylesa


2 Answers

I've just solve problem myself. I'll write for friends who face to same problem.

app.get('/a', function(req, res) {
res.render('view', { layout: 'LayoutA' });
});
app.get('/b', function(req, res) {
  res.render('view', { layout: 'LayoutB' });
});
like image 185
eylesa Avatar answered Mar 17 '23 05:03

eylesa


This is what I do:

First, I set a default layout

// app.js
app.set('layout', 'layouts/front') // assuming it's inside the 'views' directory

Then, I use middlewares for separate Router instances:

// app.js
app.use('/admin', AdminRoutes);

In my AdminRoutes.js:

// AdminRoutes.js
const router = express.Router();

router.use((req, res, next) => {
    // changing layout for my admin panel
    req.app.set('layout', 'layouts/admin');
    next();
});

router.get('/', (req, res) => {
   res.render('admin/index'); // will use admin layout
});
like image 31
Sumit Wadhwa Avatar answered Mar 17 '23 03:03

Sumit Wadhwa