0

I am facing a problem where a variable in Express/EJS is not defined and therefore the view doesn't load. Here I want to display a variable called weather on the page if defined. Instead I get the error "weather is not defined". I have also tried 'null'. This, by the way, is at the beginning. Because, when I submit the form, the weather-variable would be defined by the value from the input. So the evening over I tried around with no success. Is there a better approach or do I have a mistake in the way I want to get it done?

The following shows the code (I assume the problem is more about Express/EJS rather than Node):

<html>
  <head>

  </head>
  <body style="background-color:gray; color:black;">
    <h1>
      Hello World
    </h1>
    <form action="/form" method="post">
        <label for="team_name">Enter name: </label>
        <input id="team_name" type="text" name="name_field" value="Default name for team.">
        <input type="submit" value="OK">
    </form>

  <% if(weather !== 'undefined'){ %>
    <p><%= weather %></p>
  <% } %>

  <% if(error !== 'undefined'){ %>
    <p><%= error %></p>
  <% } %>

  </body>
</html> 

Thanks in advance.

2 Answers 2

0

Problem solved by using "locals". This is what the code looks like. I'll edit the answer asap and explain why locals are the reason it works.

  <% if(locals.weather !== 'undefined'){ %>
    <p><%= locals.weather %></p>
  <% } %>

  <% if(locals.error !== 'undefined'){ %>
    <p><%= locals.error %></p>
  <% } %>
0

That will work fine if you use typeof

<% if(typeof weather !== 'undefined'){ %>
    <p><%= weather %></p>
  <% } %>

  <% if(typeof error !== 'undefined'){ %>
    <p><%= error %></p>
  <% } %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.