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?
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' });
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With