2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2015-01-24 04:02:25 +08:00
|
|
|
module CategoryBadge
|
2015-05-18 00:38:43 +08:00
|
|
|
def self.html_for(category, opts = nil)
|
2015-01-24 04:02:25 +08:00
|
|
|
opts = opts || {}
|
|
|
|
|
|
|
|
# If there is no category, bail
|
|
|
|
return "" if category.blank?
|
|
|
|
|
|
|
|
# By default hide uncategorized
|
|
|
|
return "" if category.uncategorized? && !opts[:show_uncategorized]
|
|
|
|
|
2023-11-13 23:46:15 +08:00
|
|
|
extra_classes = "#{opts[:extra_classes]}"
|
2015-01-24 04:02:25 +08:00
|
|
|
|
2019-05-03 06:17:27 +08:00
|
|
|
result = +""
|
2015-01-24 04:02:25 +08:00
|
|
|
|
2023-11-13 23:46:15 +08:00
|
|
|
# parent class
|
|
|
|
parent_category =
|
|
|
|
Category.find_by(id: category.parent_category_id) unless category.parent_category_id.nil?
|
|
|
|
has_parent_class = parent_category ? "--has-parent" : ""
|
2015-01-24 04:02:25 +08:00
|
|
|
|
2015-05-18 00:38:43 +08:00
|
|
|
# category name
|
2023-11-13 23:46:15 +08:00
|
|
|
class_names = "badge-category #{has_parent_class}"
|
2018-06-28 16:14:55 +08:00
|
|
|
description = category.description_text ? "title='#{category.description_text}'" : ""
|
2016-04-26 23:18:34 +08:00
|
|
|
category_url =
|
|
|
|
opts[:absolute_url] ? "#{Discourse.base_url_no_prefix}#{category.url}" : category.url
|
2015-01-24 04:02:25 +08:00
|
|
|
|
2023-12-07 01:49:19 +08:00
|
|
|
# styles
|
|
|
|
styles = {
|
|
|
|
"--category-badge-color": "##{category.color}",
|
|
|
|
"--category-badge-text-color": "##{category.text_color}",
|
|
|
|
}
|
|
|
|
styles["--parent-category-badge-color"] = "##{parent_category.color}" if parent_category
|
|
|
|
style_value = styles.map { |k, v| "#{k}: #{ERB::Util.html_escape(v)};" }.join(" ")
|
|
|
|
|
2023-11-13 23:46:15 +08:00
|
|
|
# category badge structure
|
|
|
|
result << "<span data-category-id='#{category.id}'"
|
2023-12-07 01:49:19 +08:00
|
|
|
result << " style='#{style_value}'"
|
2023-11-13 23:46:15 +08:00
|
|
|
result << " data-parent-category-id='#{parent_category.id}'" if parent_category
|
|
|
|
result << " data-drop-close='true' class='#{class_names}' #{description}>"
|
|
|
|
result << "<span class='badge-category__name'>"
|
|
|
|
result << ERB::Util.html_escape(category.name)
|
|
|
|
result << "</span></span>"
|
2018-06-28 16:14:55 +08:00
|
|
|
|
2023-11-13 23:46:15 +08:00
|
|
|
# wrapping link
|
2018-11-15 21:35:50 +08:00
|
|
|
result =
|
2023-11-13 23:46:15 +08:00
|
|
|
"<a class='badge-category__wrapper #{extra_classes}' href='#{category_url}'>#{result}</a>"
|
2018-06-28 16:14:55 +08:00
|
|
|
|
|
|
|
result.html_safe
|
2015-05-13 19:25:27 +08:00
|
|
|
end
|
2015-01-24 04:02:25 +08:00
|
|
|
end
|