# frozen_string_literal: true module Jekyll module Filters module DateLocal # Translates month and day names. This requires certain values on # your _data/LANG.yml # # Example usage: # # {{ page.date | date_local: '%e de %B de %Y' }} # # @see {_data/es.yml} # @param [String|Date|Time|DateTime] # @param [String] # @return [String] def date_local(input, format) require 'date' input = ::Jekyll::Utils.parse_date(input) unless input.respond_to? :mon # Return early if we don't need to translate return input.strftime(format) unless /%(|\^)[aAbBpP]/ =~ format input.strftime translate_localization_format(input, format) rescue ArgumentError, TypeError, ::Jekyll::Errors::InvalidDateError => e Jekyll.logger.warn "#{input} is not a valid date: #{e.message}" input end private # Adapted from the i18n gem # @see {https://github.com/ruby-i18n/i18n/blob/a8f4fdcb197e56b5a698d1bc68007dd0871c03bf/lib/i18n/backend/base.rb} def translate_localization_format(object, format) format.to_s.gsub(/%(|\^)[aAbBpP]/) do |match| case match when '%a' then i18n.dig('date', 'abbr_day_names', object.wday - 1) when '%^a' then i18n.dig('date', 'abbr_day_names', object.wday - 1)&.upcase when '%A' then i18n.dig('date', 'day_names', object.wday - 1) when '%^A' then i18n.dig('date', 'day_names', object.wday - 1)&.upcase when '%b' then i18n.dig('date', 'abbr_month_names', object.mon - 1) when '%^b' then i18n.dig('date', 'abbr_month_names', object.mon - 1)&.upcase when '%B' then i18n.dig('date', 'month_names', object.mon - 1) when '%^B' then i18n.dig('date', 'month_names', object.mon - 1)&.upcase when '%p' then i18n.dig('time', object.hour < 12 ? 'am' : 'pm')&.upcase if object.respond_to? :hour when '%P' then i18n.dig('time', object.hour < 12 ? 'am' : 'pm')&.downcase if object.respond_to? :hour end end end def site @site ||= @context.registers[:site] end def i18n @i18n ||= site.data.dig site.config['lang'] end end end end Liquid::Template.register_filter(Jekyll::Filters::DateLocal)