Skip to content

Unexpected behavior when trying to initialize local variables #92

@ChrisMuc

Description

@ChrisMuc

I'm using multiple ejs templates which all include a common header tamplate, whereas the header template should be customizeable by the parent templates. Therefore, I'm using the following (simplified) structure:

index.ejs:

<% var showMenu = true; %>
<% include header%>
CONTENT

header.ejs:

<% if (typeof(showMenu) === 'undefined') { var showMenu = false; } %>
HEADER
showMenu:<%= showMenu %>

Unfortunately, the first line in header.ejs ends up in an unexpected behavior / bug!
The idea behind this line is to check whether the parent template uses customization, and if not, initialize customization-variables with defaults. But in this small example showMenu is always set to false! Just like showMenu has never been declared in the parent template!

More interestingly:
When you swap the first line in header.ejs to:

  typeof(showMenu):<%= typeof(showMenu) %>

to see if typeof() really returns 'undefined', you wil get surprised again. Instead of 'undefined' it returns the previously expected value ('boolean'):

  typeof(showMenu):boolean
  showMenu:true

So technically in our first example, showMenu should not be set to false.

If you remove the first line in index.ejs, you will also see an 'undefined'. (To actually see this value, you also have to remove the last line in header.ejs, as otherwise you will get an undefined exception)

If you are using a header.ejs like this:

typeof(showMenu):<%= typeof(showMenu) %>
HEADER
<% if (typeof(showMenu) === 'undefined') { %>
showMenu:not-set-by-parent
<% } else { %>
showMenu:<%= showMenu %>
<% }%>

everything works fine. Anyway, I would prefer the first version to work for mainly three reasons:

  • It allows me to manage defaults in on place (and not scattered across the whole template)
  • I'm also using it for other variabels like "activeMenuItem" where not using the posibility to set a variable to an default value, may cause redundant lines.
  • and most important: "if (typeof(showMenu) === 'undefined') { var showMenu = false; }" simply does not behave as expected; nor does it throw an exception to inform the user about doing something wrong!

And just in case: I don't wanna start a discussion about MVC principles. I know that logic belongs to the controller and not to templates! But in my opinion this defnitely is a bug; in particular as the codes does not behave as expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions