Search code examples
expresspug

Interpolation doesn't work in pug value attribute


I am trying to use the below markup to autopopulate the form.

textarea.form-control(rows='5',id='description' name='description', value='#{product.description}')

where product is the variable from js file.But the form doesn't autopopulate the values

route:

router.get('/update/:id', function(req, res) {
  productApi.getProductById(req.params.id, function(err, product) {

    res.render('crud/update', {product: product});
  });
});

json:

products: [
    {
      "id": 1,
      "description": "Tasty cookies"
    },
    {
      "id": 2,
      "description": "delicious candies"
    }]

Solution

  • This is how to output the form element:

    textarea.form-control(rows='5' id=product.id name='description')= product.description
    

    Notes:

    • When you put an = directly after an attribute what comes next is evaluated as an expression so you can just drop a variable name in there (without quotes)
    • When you're inside an inline expression the interpolation tags won't work (#{...} and !{...}) so just use plain variable names or template literals (template literals don't work in IE)
    • Commas are optional in pug, it will insert them where necessary in the output but you can leave them in if you like them