Szymon D
Szymon D

Reputation: 441

Node.js, Jade/Pug, how to serve full and part of template?

If request has been made via ajax, I would like to send only block content from page1.jade, if it's normal GET it should answer with this block built into layout.jade

Upvotes: 1

Views: 2245

Answers (1)

avck
avck

Reputation: 3693

Jade does not support conditional layout switch:

if type=='get'
  extends layout
block content
  p This is block content

This will render the page with the layout irrespective of the variable name.

METHOD 1

A simple way would be to define the block content in a separate file and include it in your page1.jade, you can access that block independently then.

layout.jade

html
head
title My Site - #{title}
block scripts
body
  block content
  block foot

page1.jade

extends layout

block content
  include ./includes/block.jade

includes/block.jade

p This is the block content

This would be the way to handle requests in your routes file

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get('/block', function(req, res, next) {
  res.render('includes/block', { title: 'Express' });
});

Modify it to handle the AJAX/browsers request.

METHOD 2

The other cleaner way would be modifying your layout.jade itself for conditional

layout.jade

if type=='get'
  html
  head
  title My Site - #{title}
  block scripts
body
  block content
  block foot

And passing variable from your router while rendering the same page each time:

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express',type:'get' });
});
router.get('/block', function(req, res, next) {
  res.render('index', { title: 'Block Express' });
});

Upvotes: 2

Related Questions