javascriptnode.jsexpresspugpugjs

How to render a pug view without removing existing data?


For example, I have a pug view 'VIEW.pug', it contains two parts

after request a GET from express/node, I would like to keep part A's data and refresh part B with new data by using the res.render('VIEW', {xxx}) function.

So how can I make this happen? Once I render VIEW.pug, though I refresh part B with the correct data, but the data in part A are gone.

I wanna both of part A and part B have data, A with old existing data, and B with new data.


Solution

  • create a layout.pug file :

    html
      head
        title My Site - #{title}
        block scripts
          script(src='/jquery.js')
      body
        block content
    

    now create a file with partA.pug , which extends layout file :

    -extends layout.pug
      block content
      h1= PART A
    

    now use include to include partB in partA file

     include includes/partB.pug
    

    your partB.pug should be rendered based on condition

    #partB
    - if(section=== 'DEMO-1') {
    | <p>DEMO 1</p>
    - }
    - if(section === 'DEMO-2') {
    | <p>DEMO 2</p>
    - }
    

    app.js

    var express=require('express');
    let app = express();
    app.set("view engine", "pug");
    app.set("views", path.join(__dirname, "views"));
    
    
    app.get('/demo1',function(req,res){
       return res.render("partA",{section:'DEMO-1'});
    });
    
    app.get('/demo2',function(req,res){
       return res.render("partA",{section:'DEMO-2'});
    });