【问题标题】:Convert form select box from .pug to .ejs将表单选择框从 .pug 转换为 .ejs
【发布时间】:2019-09-13 02:12:40
【问题描述】:

我正在尝试将以下内容从 pug 转换为 ejs。它是一个作者选择框(来自关联的集合),以将一本书添加到数据库的形式。当我添加一本新书时,它会引发错误“无法读取未定义的属性'_id'”指向第一个选项元素(但我可以出于某种原因更新现有的书)。而在哈巴狗版本中,它不会抛出这个错误。我的转换正确吗?

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>

【问题讨论】:

    标签: node.js pug ejs


    【解决方案1】:

    转换是正确的。这里只是一个小错误&lt;%= 而不是&lt;%

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

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

    修改此行以防止出现错误&lt;% if(typeof book !== 'undefined' &amp;&amp; 'author' in book) { %&gt;

    <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>
    

    【讨论】:

    • 就是这样。谢谢。我被抛弃了,因为错误消息由于某种原因指向第一个选项元素,而不是我忘记 = 符号的第二个元素。
    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 2013-08-28
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多