Apply custom behaviour for first/last slot #1092
Answered
by
BigBigDoudou
BigBigDoudou
asked this question in
Q&A
-
I have a "breadcrumb" component that has many "items", for example (simplified): render BreadcrumbComponent.new do |breadcrumb|
breadcrumb.item("animal")
breadcrumb.item("feline")
breadcrumb.item("cat")
end
# animal / feline / cat And the implementation looks like: class BreadcrumbComponent
renders_many :items, "BreadcrumbItemComponent"
def call
tag.ul do
items.each { |item| concat(item) }
end
end
class BreadcrumbItemComponent
def initialize(item, active: false)
# ...
end
end
end I need the last item to have the class "active", but I don't find a way to do it. Any clue? |
Beta Was this translation helpful? Give feedback.
Answered by
BigBigDoudou
Oct 10, 2021
Replies: 2 comments 2 replies
-
Something like this maybe? items.each do |item|
if item == items.first
# first item behavior
elsif item == items.last
# last item behavior
else
# other items behavior
end
end |
Beta Was this translation helpful? Give feedback.
1 reply
-
I found the solution and it was surprisingly easy, I just needed an class BreadcrumbComponent
renders_many :items, "BreadcrumbItemComponent"
def call
tag.ul do
items.last.active = true
items.each { |item| concat(item) }
end
end
class BreadcrumbItemComponent
attr_writer :active
def initialize(item)
@item = item
end
def call
html_class = +"breadcrumb"
html_class << " active" if @active
tag.li(@item, class: html_class)
end
end
end |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
BigBigDoudou
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found the solution and it was surprisingly easy, I just needed an
attr_writer
: