如何根据用户登录状态渲染HTML?使用if/else未达预期效果,是否有其他实现方式?
Hey there! Let's sort out this EJS conditional rendering issue you're facing. First, let's break down what's going wrong with your current code, then fix it and explore alternative approaches.
What's Off in Your Current Code
- Typo in the first condition: You wrote
typeof(user) === "defined"instead of"undefined"– that's why the logged-in state isn't triggering correctly. - Logic redundancy: Your second
ifchecks for the opposite condition but isn't linked to the first with anelse, which could lead to unexpected behavior if the user state is ambiguous.
Fixed If/Else Implementation (Most Readable)
This is the cleanest approach for your use case, with corrected conditions and proper mutual exclusivity:
<% if (typeof user !== "undefined" && user) { %> <li class="navlist-item user"> <a href="/user/<%= user.id %>"> <i class="far fa-user"><%= user.name %></i> </a> </li> <% } else { %> <li class="navlist-item"> <span class="get-started"> <a href="/auth/register">Sign Up</a> </span> </li> <li class="navlist-item"> <span class="get-started"> <a href="/auth/login"><span>Log In</span></a> </span> </li> <% } %>
- Added
&& userto ensure we don't render the user nav ifuserexists but is an empty object. - Switched to
elseto make the logic explicitly mutually exclusive.
Alternative Approaches
1. Ternary Operator (For Short, Simple Content)
If you prefer more concise syntax for smaller blocks of HTML, use a ternary with template literals:
<%= typeof user !== "undefined" && user ? ` <li class="navlist-item user"> <a href="/user/${user.id}"> <i class="far fa-user">${user.name}</i> </a> </li> ` : ` <li class="navlist-item"> <span class="get-started"> <a href="/auth/register">Sign Up</a> </span> </li> <li class="navlist-item"> <span class="get-started"> <a href="/auth/login"><span>Log In</span></a> </span> </li> ` %>
Note: This works best for shorter HTML snippets – readability drops for complex UI.
2. Partial Templates (For Maintainability)
If your navigation grows more complex, split the UI into partial files to keep your main template clean:
- Create
partials/nav-user.ejs(contains the logged-in user nav) - Create
partials/nav-guest.ejs(contains the signup/login nav)
Then include them conditionally in your main template:
<% if (typeof user !== "undefined" && user) { %> <% include partials/nav-user %> <% } else { %> <% include partials/nav-guest %> <% } %>
This is great for keeping code organized as your app scales.
3. Simplified Condition (If Backend Ensures User State)
If your backend guarantees that user is either a valid object (when logged in) or null/undefined (when not), you can simplify the check to:
<% if (user) { %> <!-- Logged-in nav --> <% } else { %> <!-- Guest nav --> <% } %>
Just make sure your backend never passes an empty user object, as this would still trigger the logged-in block.
内容的提问来源于stack exchange,提问作者Bhaskar

