Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS Pass a Variable to Jade / Pug

Tags:

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

like image 579
The Hawk Avatar asked Jun 26 '16 23:06

The Hawk


People also ask

What is Jade file in node js?

Jade is a template engine for node. js and the default rendering engine for the Express web framework. It is a new, simplified language that compiles into HTML and is extremely useful for web developers. Jade is designed primarily for server-side templating in node.


2 Answers

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 
like image 74
Seetpal singh Avatar answered Sep 18 '22 15:09

Seetpal singh


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

like image 31
Giorgi Maisuradze Avatar answered Sep 18 '22 15:09

Giorgi Maisuradze