Reputation: 3
How can I convert this haml code to display a dropdown of the menu items instead of a list?
Existing code within our rails 4.0 app:
app/views/application/_archive.html.haml
.sidebar-header=I18n.t('blog.archive')
-archive_dates.each do |date|
.archive-link=archive_link(date, '%B %Y')
app/models/post.rb
def self.archive_dates(audience)
archive_dates = Array.new
published.send(audience).each do |post|
archive_dates << post.publish_date.to_date if archive_dates.count == 0 || post.publish_date.month != archive_dates.last.month || post.publish_date.year != archive_dates.last.year
end
archive_dates
end
app/helpers/application_helper.rb:
def archive_link(archive_date, format)
archive_date = archive_date.to_date
link_to I18n.l(archive_date, format: format), posts_path(month: archive_date.month, year: archive_date.year)
end
This is the output HTML.
https://i.sstatic.net/bFaxf.png
Users are able to select a month and display all posts made during that month. I am looking for the same format and behaviour, but must use a dropdown menu instead.
Upvotes: 0
Views: 1222
Reputation: 8003
This would show a drop down menu with labels as the formatted link tags and values as the actual link.
= select_tag "name_of_tag" , options_for_select( archive_dates.map{ |date|
[archive_link(date, '%B %Y').html_safe, #label
posts_path(month: date.month, year: date.year), #value
:class => "archive_date" ] # class of each option
}), onchange: "window.location = this.options[this.selectedIndex].value;"
Need to use html_safe
for each label to make it appear as raw html.
Added the onchange
html option to take the user to the selected option whenever it is selected.
Upvotes: 0
Reputation: 3477
You can use the select tag in your view for e.g.
= select_tag 'user_id', options_for_select(@users.collect{ |u| [u.name, u.id] })
# change the value of options_for_select as per your requirement
Upvotes: 2