How can I use a local (or for each) variable in Sinatra with Haml particles?

I have a partial Haml part in Sinatra to handle all of my "open pages", such as meta tags.

I would like to have a variable for page_title in this partial, and then set this variable for each view.

Something like this in partial:

%title @page_title 

Then in the view, let me do something like:

 @page_title = "This is the page title, BOOM!" 

I read a lot of questions / posts, etc., but I don’t know how to ask for a solution to what I'm trying to do. I come from Rails, where our developers usually used content_for, but they installed it all. I am really trying to understand how this works. It seems that I should define it and use it: local residents somehow, but I did not understand this. Thank you in advance for any advice!

+7
source share
1 answer

You pass variables to partial parts of Sinatra haml as follows:

page.haml

 !!! %html{:lang => 'eng'} %body = haml :'_header', :locals => {:title => "BOOM!"} 

_header.haml

  %head %meta{:charset => 'utf-8'} %title= locals[:title] 

In the case of the page name, I just do something like this in the btw layout:

layout.haml

 %title= @title || 'hardcoded title default' 

Then set the @title value in the routes (with an assistant so that it is short).

But if your title is partial, you can combine two examples, for example:

layout.haml

 !!! %html{:lang => 'eng'} %body = haml :'_header', :locals => {:title => @title} 

_header.haml

  %head %meta{:charset => 'utf-8'} %title= locals[:title] 

app.rb

 helpers do def title(str = nil) # helper for formatting your title string if str str + ' | Site' else 'Site' end end end get '/somepage/:thing' do # declare it in a route @title = title(params[:thing]) end 
+12
source

All Articles