I have a Haml partial in Sinatra to handle all of my 'page open' items like meta tags.
I would love to have a variable for page_title in this partial and then set that variable per view.
Something like this in the partial:
%title @page_title
Then in the view, be allowed to do something like:
@page_title = "This is the page title, BOOM!"
I have read a lot of questions/posts, etc. but I don't know how to ask for the solution to what I am trying to do. I'm coming from Rails where our devs usually used content_for but they set all that up. I'm really trying to learn how this works. It seems like I have to define it and use :locals in some way but I haven't figured it out. Thank you in advance for any tips!
You pass variables into Sinatra haml partials like this:
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 a page title I just do something like this in my layout btw:
layout.haml
%title= @title || 'hardcoded title default'
Then set the value of @title in routes (with a helper to keep it short).
But if your header is a partial then you can combine the two examples like:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With