1

I'm using Node.js and ejs for templating language.

I feel like this is really silly and I should be able to solve it, but I'm stuck.

I am having trouble with the following function:

// Returns true if campground has been posted by currently logged on user
// If no user logged on, returns false
function checkIfCampgroundBelongsToUser(campgroundAuthorID) {
    var currentUser = <%-JSON.stringify(currentUser) %>
    if(currentUser && currentUser._id === campgroundAuthorID) { 
        return true;
    }
    return false;
}

This code works fine when a user is logged in. However, when no user is logged in evaluates to empty. Not empty string. Not null. Not undefined. Just empty. Thus, I get the following error

Uncaught SyntaxError: Unexpected token if

When I inspect via chrome dev tools, this is what I see

enter image description here

(yes I realize a semi-colon is missing, I added it... And when I do, I get uncaught syntaxError: Unexpected token ;)

1
  • You could try -> <%-currentUser ? JSON.stringify(currentUser) : "null" %> Commented Oct 26, 2017 at 22:11

1 Answer 1

1

undefined will pass through JSON.stringify unchanged and EJS will render that as nothing. If you default it to null it'll be converted to the string "null", which EJS will render as null.

var currentUser = <%- JSON.stringify(currentUser || null) %>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.