动态添加category
const categories = ['fruit', 'vagetable', 'diary', 'unique'];
app.get('/products/new', (req, res) => { res.render('products/new', { categories }) })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New product</title> </head> <body> <h1>Add a product </h1> <form action="/products" method="POST"> <label for="name">Name</label> <input type="text" name="name" id="name" placeholder="product name"> <label for="price">price</label> <input type="number" name="price" id="price" placeholder="price"> <label for="category">Select category</label> <select name="category" id="category"> <%for(let category of categories){%> <option value="<%=category>"> <%=category> </option> <%}%> </select> <button>Submit</button> <!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',...)连接着 --> </form> </body> </html>
new.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New product</title> </head> <body> <h1>Add a product </h1> <form action="/products" method="POST"> <label for="name">Name</label> <input type="text" name="name" id="name" placeholder="product name"> <label for="price">price</label> <input type="number" name="price" id="price" placeholder="price"> <label for="category">Select category</label> <select name="category" id="category"> <%for(let category of categories){%> <option value="<%=category>"> <%=category> </option> <%}%> </select> <button>Submit</button> <!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',。。。)连接着 --> </form> </body> </html>
edit.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit product</title> </head> <body> <h1>Edit a product </h1> <form action="/products/<%=product._id%>?_method=PUT" method="POST"> <label for="name">Name</label> <input type="text" name="name" id="name" placeholder="product name" value="<%=product.name%>"> <label for="price">price</label> <input type="number" name="price" id="price" placeholder="price" value="<%=product.price%>"> <label for="category">Select category</label> <select name="category" id="category"> <%for(let category of categories){%> <option value="<%=category%>" <%=product.category===category ? 'selected' : '' %>><%=category%> </option> <%}%> </select> <button>Submit</button> <!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',......)连接着 --> </form> <a href="/products/<%=product._id%>">Cancel</a> </body> </html>
<option value="<%=category%>" <%=product.category===category ? 'selected' : '' %>><%=category%> </option>
设置默认显示的category。