如何在EJS模板中编写或条件?代码排查:仅满足第一个条件
Hey there! Let's dig into why your EJS condition only triggers for user === 0 and not user === 1. I've dealt with similar gotchas before, so let's break this down step by step:
1. Check the Type of Your user Variable
The most common culprit here is a type mismatch. If your user value is actually a string (like "1" instead of the number 1), the strict equality operator (===) will fail because it checks both value and type.
To confirm this, add a quick debug log in your template:
<% console.log("User value:", user, "| Type:", typeof user) %>
If the output shows User value: 1 | Type: string, you have two solid fixes:
Option 1: Match the string type directly
<% if (user === 0 || user === "1") { %> <div id="main_div"> My content over here </div> <% } %>
Option 2: Convert user to a number first
<% const userId = Number(user); %> <% if (userId === 0 || userId === 1) { %> <div id="main_div"> My content over here </div> <% } %>
2. Verify user is Being Passed Correctly
Double-check that your backend is actually passing the value 1 to the template when you expect it. Sometimes typos in variable names or incorrect data fetching can lead to unexpected values. Add a debug line right before your condition to confirm:
<% console.log("Current user value passed to template:", user) %>
3. Test the Condition in Isolation
To rule out any weird interactions with surrounding code, test the user === 1 condition on its own first:
<% if (user === 1) { %> <div> User is 1 - this should show up if the value is correct </div> <% } %>
If this works, the issue was likely a type/value mismatch (since your original || logic looks perfectly valid).
Remember, EJS runs standard JavaScript under the hood, so any debugging tricks you use in regular JS work here too!
内容的提问来源于stack exchange,提问作者Anuja vinod

