Node JS Pass a Variable to Jade / Pug
Asked Answered
L

2

26

For some reason I can't pass a variable to the pug template with Node JS.

app.get("/", function (req, res) {
    res.render('index', { hello : 'Hey'} )
})

....

extends layout.pug

block content
    h1 #{hello} guy

This just returns "guy" in the index.html file

Longley answered 26/6, 2016 at 23:51 Comment(1)
can you put more code? what is app? what does layout.pug have?Marissamarist
P
23

I think you are using JADE coding (#{hello}) with "pug"(updated jade) plugin with static .html -- completely wrong.

Follow the lines below:

  1. Use this first
app.set('views', __dirname + '/public/views');
app.set('view engine', 'pug');
  1. Then pass this to first visit
app.get('/', function (req, res) {
   res.render('index', { title: 'Hey', message: 'Hello there!'});
});
  1. Then echo in template file "index.pug" in "/public/views"
html
  head
  title= title
body
  h1= message
Payton answered 27/6, 2016 at 6:23 Comment(3)
give me your directory structure snapshot + show me your server file with app.set('views', __dirname + '/public/views'); app.set('view engine', 'pug'); than pass this to first visit app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); });Payton
Now it just says "Express" github.com/jpking72/nodejsfiddle.gitLongley
i'm having the same issue, and apparently @Seetpalsingh not sure what TheHawk and i are not getting right.Oligocene
T
15

Try this.. works for me.

nodejs part / index.js

const router = require('express').Router();
router.get('/', (req, res, next) => {
    const testObj = {hello: 'Hey'};
    res.render('index', { testObj: JSON.stringify(testObj) });
});

pug/jade part / (index.pug)

script.
    var testObj = !{testObj};

i'm using pug version: 2.0.3

Tannen answered 7/5, 2018 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.