I am having a problem to convert the following Ejs to pug

Issue

I am having a problem to convert the following Ejs to pug

in admin/edit-product.ejs
we can make changes with product already we have it
but But I want to transfer ejs to pug
any solutions

<form class="product-form" action="/admin/<% if (editing) { %>edit-product<% } else { %>add-product<% } %>" method="POST">

in admin.js controller

 exports.getAddProduct = (req, res, next) => {
    res.render('admin/edit-product', {
      pageTitle: 'Add Product',
      path: '/admin/add-product',
      editing: false
    });
  };

  exports.postAddProduct=(req, res, next) => {
    const title=req.body.title;
    const imageUrl=req.body.imageUrl;
    const price=req.body.price;
    const description=req.body.description;
    const product=new Product(title,imageUrl,description,price);
    product.save();
    res.redirect('/');
  }; 
  exports.getEditProduct = (req, res, next) => {
    const editMode = req.query.edit;
    if (!editMode) {
      return res.redirect('/');
    }
    const prodId = req.params.productId;
    Product.findById(prodId, product => {
      if (!product) {
        return res.redirect('/');
      }
      res.render('admin/edit-product', {
        pageTitle: 'Edit Product',
        path: '/admin/edit-product',
        editing: editMode,
        product: product
      });
    });
  };

Solution

Pug supports inline JavaScript code, so you could use a ternary conditional within some attribute interpolation like this:

form.product-form(action='/admin/' + (editing ? 'edit' : 'add') + '-product', method='POST')

Or for a more readable approach, construct the action path beforehand in a code block and store it in a variable:

-
  let actionPath
  if (editing) {
    actionPath = '/admin/edit-product'
  } else {
    actionPath = '/admin/add-product'
  }

form.product-form(action= actionPath, method='POST')

Answered By – Sean

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.