1

I have two files. One is a pug file:

doctype html
html
head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1, shrink-to-fit=no')
    link(href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', rel='stylesheet')
    title Your first page
body
    script(src='https://code.jquery.com/jquery-3.3.1.min.js')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js')
    script(src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js')

and the second one is a JS file:

var express = require('express'),
    logger = require('morgan');
var app = express();
var x = 1;
var y = 2;
 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'pug');         
app.use(logger('dev'));                        
app.use(express.static(__dirname + '/public')); 
 
app.get('/', function (req, res) {      
    res.render('index', {pretty:true}); 
});
 
app.listen(3000, function () {                  
    console.log('The application is available on port 3000');
});

Now I'd like to use x and y variables and display them using the pug file. How can I do this?

Eno_
  • 41
  • 7

2 Answers2

1

In your code, you're already passing a variable to the template (pug). You do it in the same way:

app.get('/', function (req, res) {      
   res.render('index', {pretty:true, x: x, y: y}); 
});

The x: is the "key" and the x is the reference to your variable x. The same procedure with y.

In your pug file e.g :

h1 = x
h2 = y

Or if you're using HTML in your .pug file you can use:

<p>  
  !{x}
</p>

<p>  
  !{y}
</p>
Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
florianjr
  • 31
  • 3
1

Try this.

  1. Pass the variable to your view
app.get('/', function (req,res) { 
    res.render('index', { pretty: true, title: 'Hey', message: 'Hello there!'}); 
});
  1. then echo in template file "index.pug" in "/public/views"
doctype html
html
head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1, shrink-to-fit=no')
    link(href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', rel='stylesheet')
    title Your first page
    title= title
body
    script(src='https://code.jquery.com/jquery-3.3.1.min.js')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js')
    script(src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js')

    h1=message

Hope that helps.

jaye_
  • 11
  • 1