In with my last post on creating a notification badge I showed the HTML and CSS markup. But I forgot that even when the notification count was at zero it still showed the badge.
Because was using a Rails app I wanted to continue using the
link_to helper method.
I created a new helper method called
link_to_with_notifications that allowed me to use all the features of
link_to and only add the badge if the value was not zero.
def link_to_with_notifications(*args, &block) # get notification count from hash notifications = args[:notifications] || 0 # create the data- attribute unless notifications.zero? args['data-notifications'] = notifications unless notifications.zero? # delete original notifications hash args.delete(:notifications) # run original link_to helper link_to(*args, &block) end
<%= link_to_with_notifications 'Completed Orders', user_carts_path(user, view: 'completed'), class: 'button', notifications: user.open_orders.count %>