将表单 select 框从 .pug 转换为 .ejs

Convert form select box from .pug to .ejs

我正在尝试将以下内容从 pug 转换为 ejs。它是一个 select 作者框(来自关联的集合),用于将一本书添加到数据库。当我添加一本新书时,它会抛出错误 "Cannot read property '_id' of undefined" 指向第一个选项元素(但由于某种原因我可以更新现有的书)。在 pug 版本中,它不会抛出此错误。我的转换正确吗?

select#author.form-control(type='select', placeholder='Select author' name='author' required='true' )
  - authors.sort(function(a, b) {let textA = a.family_name.toUpperCase(); let textB = b.family_name.toUpperCase(); return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;});
  for author in authors
    if book
      option(value=author._id selected=(author._id.toString()==book.author._id.toString() ? 'selected' : false) ) #{author.name}
    else
      option(value=author._id) #{author.name}

我的转换:

<select class="form-control" id="author" type="select" placeholder="Select author" name="author" required="true">
  <% authors.sort(function(a, b) {let textA = a.family_name.toUpperCase(); let textB = b.family_name.toUpperCase(); return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;}); %>
  <% authors.forEach(function(author) { %>
    <% if(typeof book !== 'undefined') { %>
      <option value="<%= author._id %>" selected=<%= (author._id.toString() == book.author._id.toString()) ? 'selected' : 'false' %>><%= author.name %></option>
    <% } else { %>
      <option value="<% author._id %>"><%= author.name %></option>
    <% } %>
  <% }) %>
</select>

转换正确。这里只是一个小错误 <%= 而不是 <%

<option value="<%= author._id %>"><%= author.name %></option>

出于任何原因 book.author 不存在。 Pug 正在捕获未定义的变量并继续渲染,而 ejs 则没有。所以你的数据有问题。

修改此行以防止错误<% if(typeof book !== 'undefined' && 'author' in book) { %>

<select class="form-control" id="author" type="select" placeholder="Select author" name="author" required="true">
  <% authors.sort(function(a, b) {let textA = a.family_name.toUpperCase(); let textB = b.family_name.toUpperCase(); return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;}); %>
  <% authors.forEach(function(author) { %>
    <% if(typeof book !== 'undefined' && 'author' in book) { %>
      <option value="<%= author._id %>" selected=<%= (author._id.toString() == book.author._id.toString()) ? 'selected' : 'false' %>><%= author.name %></option>
    <% } else { %>
      <option value="<%= author._id %>"><%= author.name %></option>
    <% } %>
  <% }) %>
</select>