简体   繁体   中英

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

如果请求是通过ajax发出的,我只想发送来自page1.jade的块内容,如果是正常的GET,则应使用内置在layout.jade中的该块来回答

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM