How i handle a variable in a value attribute on a html tag in EJS?

63 Views Asked by At

i am following the odin project, in the node lesson they use Jade but i am using Ejs for the template language. I have the following code:

    <%- include ./partials/startBody.ejs %>

<div class="col-sm-10">
  <h1><%= title %></h1>

  <form method="POST" action="">
    <div class="form-group">
      <label for="name">Genre:</label>
      <input id="name" class="form-control" type="text" placeholder="Fantasy, Poetry etc." name="name" value="<%= genre.name %> "/>
    </div>
    <button class="btn btn-primary" type="submit">Submit</button>
  </form>
  <% if (typeof errors !== "undefined") { %>
    <ul>
      <% for (var error of errors) { %>
        <li><%= error.msg %></li>
      <% } %>
    </ul>
  <% } %>

<%- include ./partials/endBody.ejs %>

This route needs to handle the form when the user input incomplete data so it has to return the data typed, i have the problem where when first rendering the view the input with the name id has no value because there is no genre defined,

      <input id="name" class="form-control" type="text" placeholder="Fantasy, Poetry etc." name="name" value="<%= genre.name %> "/>

I tried also the following:

      <input id="name" class="form-control" type="text" placeholder="Fantasy, Poetry etc." name="name" value="<%= if (typeof genre.name !== &quotundefined&quot) {genre.name}%> "/>

But then it not recognizes the if, How can i handle this?

Thanks a lot!

1

There are 1 best solutions below

1
Siddarth Zl On

You can use a ternary operator to check if genre exists before trying to access its name property. Here's an example:

<input id="name" class="form-control" type="text" placeholder="Fantasy, 
Poetry etc." name="name" value="<%= (genre && genre.name) ? genre.name : 
'' %>"/>

This code checks if genre exists and has a name property. If so, it sets the input's value to genre.name. Otherwise, it sets the value to an empty string. This way, the input will have a default value of an empty string if genre is not defined.

The ternary operator condition ? valueIfTrue : valueIfFalse is a shorthand way to write an if statement. In this case, the condition is (genre && genre.name), which checks if genre exists and has a name property. If this is true, the value of the input is set to genre.name. If not, it's set to an empty string.