Thursday 4 May 2017

Pug process/expand variables inside a variable

I'm using Pug with Express and I'd like Pug to process variables that are inside other variables, is this possible?

So in the example below I have the #{name} variable inside the #{website.greeting} variable which should resolve to Henry when the template is rendered.

Content file:

//data.json
{
  "heading": "Welcome to this website.",
  "greeting": "Hello #{name}, how are you today?"
}

Express code:

//app.js
app.use(function (req, res, next) {
  res.locals.website = parseJsonFile('data.json')
  next()
}

function parseJsonFile(filename) {...}

//index.js
router.get('/', function (req, res, next) {
  var context = {
    name: 'Henry'
  }
  res.render('template', context)
}

Pug template:

//template.pug
html
  body
    h1 #{website.heading}
    p #{website.greeting}

Desired output:

<html>
  <body>
    <h1>Welcome to this website.</h1>
    <p>Hello Henry, how are you today?</p>

Is this possible, or should I simply do a find & replace on the res.locals.website variable before rendering the template with pug?

Thanks.



via Henry

No comments:

Post a Comment