Access expose in layout

Hello,

I exposed information about if a user is logged in in the base action.rb. I can access those exposes in the template, but not the layout. Is there. a trick I am missing to access the exposed variables in the layout?

# app/view.rb
    expose :authenticated
    expose :current_user

In the individual page the values render

#app/templates/health/status.html.erb
<% if authenticated %>
  <%= current_user.display_name %>
<% else %>
  <%= link_to "Login", routes.path(:user_login) %>
<% end %>

In the layout I get an error about an unknown variable authenticated

#app/templates/layouts/app.html.erb
<% if authenticated %>
  <%= current_user.display_name %>
<% else %>
  <%= link_to "Login", routes.path(:user_login) %>
<% end %>

Hey Carolyn, it’s been a while. :wave:

Yes, you need to use the Context for this. Here’s an example (pay attention to how I define the #page_title method) in my Milestoner gem which uses Hanami View for static site generation (i.e. release notes). This then gets used in the page.html.erb layout.

Hi Brooke!

Thank you! The context was exactly what I needed.

1 Like

Just curious, would the layout: true argument passed to expose also work ? It seems even simpler, but I might be missing things about contexts

expose :authenticated, layout: true
expose :current_user, layout: true
1 Like

Just checked and you are correct. An exposure with layout: true does work. Apologies for asking about a documented feature. My only excuse is the search in the guides only returns version V1.3 results, which means I a left to scroll for v2.2 syntax.

Thanks for the feedback. I sometimes switch version of doc without noticing too…