cannot share varibles between ejs files
I am building a website and want to conditionally render a given page. For that I have created this condition
<% let view_condition = (allowed_roles.includes(main_user.role) && meeting[enabled_property]) || main_user.role === 'admin' %>
this works fine for me. But I want this condition in a partial and I want to pass allowed roles and enabled_property to it. So I created a partial and included it in the main.ejs file but it showed the error that view_condition is not defined.
I tried using both tags but it did not work for me <%- include('./partials/view_condition') %> and <% include('./partials/view_condition') %>.
I know the path is correct because when I use a h1 tag in view_condition.ejs it renders properly
main.ejs file (that is not working)
<%- include('./apartials/view_condition',{allowed_roles : ['crew','client'],enabled_property : 'call_in_enabled'}) %>
<% if (view_condition) { %>
<!-- application code-->
<% } else{ %>
<div style="position: absolute;width: 100%;top: 50vh;display: flex;justify-content: center;">
<h1> you are not authorized to view this page</h1>
</div>
<% } %>
view_condition.ejs file (I tried using both let and var to declare varible)
<% let view_condition = (allowed_roles.includes(main_user.role) && meeting[enabled_property]) || main_user.role === 'admin' %>
main.ejs file (that is working)
<% let allowed_roles = ['admin', 'crew','client'] %>
<% let enabled_property = 'call_in_enabled' %>
<% let view_condition = (allowed_roles.includes(main_user.role) && meeting[enabled_property]) || main_user.role === 'admin' %>
<% if (view_condition) { %>
<!-- application code-->
<% } else{ %>
<div style="position: absolute;width: 100%;top: 50vh;display: flex;justify-content: center;">
<h1> you are not authorized to view this page</h1>
</div>
<% } %>
Would I be right in assuming you don't want to use the format that allows you to pass variables directly?
<%- include('partial.ejs',{variableToPass: "test"}) %>
Then refer to it in your partial like
<%= variableToPass %>
If you want to pass it with all the other variables, I think you might have issues with scoping those variables because they're defined as part of the partial. It may be worth trying to define them outside of the partial if it's possible. Functionally the same should work if you pass it alongside your object as include's second argument but this might not be your preference.
I would say though, you're passing the whole list of local variables each time using that method. I think that could eventually impact performance.