module Liquid::StandardFilters

Constants

HTML_ESCAPE
HTML_ESCAPE_ONCE_REGEXP
MAX_INT
STRIP_HTML_BLOCKS
STRIP_HTML_TAGS

Attributes

context[R]

Public Instance Methods

abs(input) click to toggle source

absolute value

# File lib/liquid/standardfilters.rb, line 421
def abs(input)
  result = Utils.to_number(input).abs
  result.is_a?(BigDecimal) ? result.to_f : result
end
append(input, string) click to toggle source

add one string to another

# File lib/liquid/standardfilters.rb, line 342
def append(input, string)
  input.to_s + string.to_s
end
at_least(input, n) click to toggle source
# File lib/liquid/standardfilters.rb, line 475
def at_least(input, n)
  min_value = Utils.to_number(n)

  result = Utils.to_number(input)
  result = min_value if min_value > result
  result.is_a?(BigDecimal) ? result.to_f : result
end
at_most(input, n) click to toggle source
# File lib/liquid/standardfilters.rb, line 483
def at_most(input, n)
  max_value = Utils.to_number(n)

  result = Utils.to_number(input)
  result = max_value if max_value < result
  result.is_a?(BigDecimal) ? result.to_f : result
end
base64_decode(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 71
def base64_decode(input)
  Base64.strict_decode64(input.to_s)
rescue ::ArgumentError
  raise Liquid::ArgumentError, "invalid base64 provided to base64_decode"
end
base64_encode(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 67
def base64_encode(input)
  Base64.strict_encode64(input.to_s)
end
base64_url_safe_decode(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 81
def base64_url_safe_decode(input)
  Base64.urlsafe_decode64(input.to_s)
rescue ::ArgumentError
  raise Liquid::ArgumentError, "invalid base64 provided to base64_url_safe_decode"
end
base64_url_safe_encode(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 77
def base64_url_safe_encode(input)
  Base64.urlsafe_encode64(input.to_s)
end
capitalize(input) click to toggle source

capitalize words in the input centence

# File lib/liquid/standardfilters.rb, line 41
def capitalize(input)
  input.to_s.capitalize
end
ceil(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 463
def ceil(input)
  Utils.to_number(input).ceil.to_i
rescue ::FloatDomainError => e
  raise Liquid::FloatDomainError, e.message
end
compact(input, property = nil) click to toggle source

Remove nils within an array provide optional property with which to check for nil

# File lib/liquid/standardfilters.rb, line 282
def compact(input, property = nil)
  ary = InputIterator.new(input, context)

  if property.nil?
    ary.compact
  elsif ary.empty? # The next two cases assume a non-empty array.
    []
  else
    ary.reject do |item|
      item[property].nil?
    rescue TypeError
      raise_property_error(property)
    rescue NoMethodError
      return nil unless item.respond_to?(:[])
      raise
    end
  end
end
concat(input, array) click to toggle source
# File lib/liquid/standardfilters.rb, line 346
def concat(input, array)
  unless array.respond_to?(:to_ary)
    raise ArgumentError, "concat filter requires an array argument"
  end
  InputIterator.new(input, context).concat(array)
end
date(input, format) click to toggle source

Reformat a date using Ruby's core Time#strftime( string ) -> string

%a - The abbreviated weekday name (``Sun'')
%A - The  full  weekday  name (``Sunday'')
%b - The abbreviated month name (``Jan'')
%B - The  full  month  name (``January'')
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (``AM''  or  ``PM'')
%s - Number of seconds since 1970-01-01 00:00:00 UTC.
%S - Second of the minute (00..60)
%U - Week  number  of the current year,
        starting with the first Sunday as the first
        day of the first week (00..53)
%W - Week  number  of the current year,
        starting with the first Monday as the first
        day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character

See also: http://www.ruby-doc.org/core/Time.html#method-i-strftime
# File lib/liquid/standardfilters.rb, line 394
def date(input, format)
  return input if format.to_s.empty?

  return input unless (date = Utils.to_date(input))

  date.strftime(format.to_s)
end
default(input, default_value = '', options = {}) click to toggle source

Set a default value when the input is nil, false or empty

Example:

{{ product.title | default: "No Title" }}

Use `allow_false` when an input should only be tested against nil or empty and not false.

Example:

{{ product.title | default: "No Title", allow_false: true }}
# File lib/liquid/standardfilters.rb, line 501
def default(input, default_value = '', options = {})
  options = {} unless options.is_a?(Hash)
  false_check = options['allow_false'] ? input.nil? : !Liquid::Utils.to_liquid_value(input)
  false_check || (input.respond_to?(:empty?) && input.empty?) ? default_value : input
end
divided_by(input, operand) click to toggle source

division

# File lib/liquid/standardfilters.rb, line 442
def divided_by(input, operand)
  apply_operation(input, operand, :/)
rescue ::ZeroDivisionError => e
  raise Liquid::ZeroDivisionError, e.message
end
downcase(input) click to toggle source

convert an input string to DOWNCASE

# File lib/liquid/standardfilters.rb, line 31
def downcase(input)
  input.to_s.downcase
end
escape(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 45
def escape(input)
  CGI.escapeHTML(input.to_s) unless input.nil?
end
Also aliased as: h
escape_once(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 50
def escape_once(input)
  input.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
end
first(array) click to toggle source

Get the first element of the passed in array

Example:

{{ product.images | first | to_img }}
# File lib/liquid/standardfilters.rb, line 407
def first(array)
  array.first if array.respond_to?(:first)
end
floor(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 469
def floor(input)
  Utils.to_number(input).floor.to_i
rescue ::FloatDomainError => e
  raise Liquid::FloatDomainError, e.message
end
h(input)
Alias for: escape
join(input, glue = ' ') click to toggle source

Join elements of the array with certain character between them

# File lib/liquid/standardfilters.rb, line 165
def join(input, glue = ' ')
  InputIterator.new(input, context).join(glue)
end
last(array) click to toggle source

Get the last element of the passed in array

Example:

{{ product.images | last | to_img }}
# File lib/liquid/standardfilters.rb, line 416
def last(array)
  array.last if array.respond_to?(:last)
end
lstrip(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 144
def lstrip(input)
  input.to_s.lstrip
end
map(input, property) click to toggle source

map/collect on a given property

# File lib/liquid/standardfilters.rb, line 265
def map(input, property)
  InputIterator.new(input, context).map do |e|
    e = e.call if e.is_a?(Proc)

    if property == "to_liquid"
      e
    elsif e.respond_to?(:[])
      r = e[property]
      r.is_a?(Proc) ? r.call : r
    end
  end
rescue TypeError
  raise_property_error(property)
end
minus(input, operand) click to toggle source

subtraction

# File lib/liquid/standardfilters.rb, line 432
def minus(input, operand)
  apply_operation(input, operand, :-)
end
modulo(input, operand) click to toggle source
# File lib/liquid/standardfilters.rb, line 448
def modulo(input, operand)
  apply_operation(input, operand, :%)
rescue ::ZeroDivisionError => e
  raise Liquid::ZeroDivisionError, e.message
end
newline_to_br(input) click to toggle source

Add <br /> tags in front of all newlines in input string

# File lib/liquid/standardfilters.rb, line 359
def newline_to_br(input)
  input.to_s.gsub(/\r?\n/, "<br />\n")
end
plus(input, operand) click to toggle source

addition

# File lib/liquid/standardfilters.rb, line 427
def plus(input, operand)
  apply_operation(input, operand, :+)
end
prepend(input, string) click to toggle source

prepend a string to another

# File lib/liquid/standardfilters.rb, line 354
def prepend(input, string)
  string.to_s + input.to_s
end
remove(input, string) click to toggle source

remove a substring

# File lib/liquid/standardfilters.rb, line 327
def remove(input, string)
  replace(input, string, '')
end
remove_first(input, string) click to toggle source

remove the first occurrences of a substring

# File lib/liquid/standardfilters.rb, line 332
def remove_first(input, string)
  replace_first(input, string, '')
end
remove_last(input, string) click to toggle source

remove the last occurences of a substring

# File lib/liquid/standardfilters.rb, line 337
def remove_last(input, string)
  replace_last(input, string, '')
end
replace(input, string, replacement = '') click to toggle source

Replace occurrences of a string with another

# File lib/liquid/standardfilters.rb, line 302
def replace(input, string, replacement = '')
  input.to_s.gsub(string.to_s, replacement.to_s)
end
replace_first(input, string, replacement = '') click to toggle source

Replace the first occurrences of a string with another

# File lib/liquid/standardfilters.rb, line 307
def replace_first(input, string, replacement = '')
  input.to_s.sub(string.to_s, replacement.to_s)
end
replace_last(input, string, replacement) click to toggle source

Replace the last occurrences of a string with another

# File lib/liquid/standardfilters.rb, line 312
def replace_last(input, string, replacement)
  input = input.to_s
  string = string.to_s
  replacement = replacement.to_s

  start_index = input.rindex(string)

  return input unless start_index

  output = input.dup
  output[start_index, string.length] = replacement
  output
end
reverse(input) click to toggle source

Reverse the elements of an array

# File lib/liquid/standardfilters.rb, line 259
def reverse(input)
  ary = InputIterator.new(input, context)
  ary.reverse
end
round(input, n = 0) click to toggle source
# File lib/liquid/standardfilters.rb, line 454
def round(input, n = 0)
  result = Utils.to_number(input).round(Utils.to_number(n))
  result = result.to_f if result.is_a?(BigDecimal)
  result = result.to_i if n == 0
  result
rescue ::FloatDomainError => e
  raise Liquid::FloatDomainError, e.message
end
rstrip(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 148
def rstrip(input)
  input.to_s.rstrip
end
size(input) click to toggle source

Return the size of an array or of an string

# File lib/liquid/standardfilters.rb, line 26
def size(input)
  input.respond_to?(:size) ? input.size : 0
end
slice(input, offset, length = nil) click to toggle source
# File lib/liquid/standardfilters.rb, line 87
def slice(input, offset, length = nil)
  offset = Utils.to_integer(offset)
  length = length ? Utils.to_integer(length) : 1

  if input.is_a?(Array)
    input.slice(offset, length) || []
  else
    input.to_s.slice(offset, length) || ''
  end
end
sort(input, property = nil) click to toggle source

Sort elements of the array provide optional property with which to sort an array of hashes or drops

# File lib/liquid/standardfilters.rb, line 171
def sort(input, property = nil)
  ary = InputIterator.new(input, context)

  return [] if ary.empty?

  if property.nil?
    ary.sort do |a, b|
      nil_safe_compare(a, b)
    end
  elsif ary.all? { |el| el.respond_to?(:[]) }
    begin
      ary.sort { |a, b| nil_safe_compare(a[property], b[property]) }
    rescue TypeError
      raise_property_error(property)
    end
  end
end
sort_natural(input, property = nil) click to toggle source

Sort elements of an array ignoring case if strings provide optional property with which to sort an array of hashes or drops

# File lib/liquid/standardfilters.rb, line 191
def sort_natural(input, property = nil)
  ary = InputIterator.new(input, context)

  return [] if ary.empty?

  if property.nil?
    ary.sort do |a, b|
      nil_safe_casecmp(a, b)
    end
  elsif ary.all? { |el| el.respond_to?(:[]) }
    begin
      ary.sort { |a, b| nil_safe_casecmp(a[property], b[property]) }
    rescue TypeError
      raise_property_error(property)
    end
  end
end
split(input, pattern) click to toggle source

Split input string into an array of substrings separated by given pattern.

Example:

<div class="summary">{{ post | split '//' | first }}</div>
# File lib/liquid/standardfilters.rb, line 136
def split(input, pattern)
  input.to_s.split(pattern.to_s)
end
strip(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 140
def strip(input)
  input.to_s.strip
end
strip_html(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 152
def strip_html(input)
  empty  = ''
  result = input.to_s.gsub(STRIP_HTML_BLOCKS, empty)
  result.gsub!(STRIP_HTML_TAGS, empty)
  result
end
strip_newlines(input) click to toggle source

Remove all newlines from the string

# File lib/liquid/standardfilters.rb, line 160
def strip_newlines(input)
  input.to_s.gsub(/\r?\n/, '')
end
times(input, operand) click to toggle source

multiplication

# File lib/liquid/standardfilters.rb, line 437
def times(input, operand)
  apply_operation(input, operand, :*)
end
truncate(input, length = 50, truncate_string = "...") click to toggle source

Truncate a string down to x characters

# File lib/liquid/standardfilters.rb, line 99
def truncate(input, length = 50, truncate_string = "...")
  return if input.nil?
  input_str = input.to_s
  length    = Utils.to_integer(length)

  truncate_string_str = truncate_string.to_s

  l = length - truncate_string_str.length
  l = 0 if l < 0

  input_str.length > length ? input_str[0...l].concat(truncate_string_str) : input_str
end
truncatewords(input, words = 15, truncate_string = "...") click to toggle source
# File lib/liquid/standardfilters.rb, line 112
def truncatewords(input, words = 15, truncate_string = "...")
  return if input.nil?
  input = input.to_s
  words = Utils.to_integer(words)
  words = 1 if words <= 0

  wordlist = begin
    input.split(" ", words + 1)
  rescue RangeError
    raise if words + 1 < MAX_INT
    # e.g. integer #{words} too big to convert to `int'
    raise Liquid::ArgumentError, "integer #{words} too big for truncatewords"
  end
  return input if wordlist.length <= words

  wordlist.pop
  wordlist.join(" ").concat(truncate_string.to_s)
end
uniq(input, property = nil) click to toggle source

Remove duplicate elements from an array provide optional property with which to determine uniqueness

# File lib/liquid/standardfilters.rb, line 239
def uniq(input, property = nil)
  ary = InputIterator.new(input, context)

  if property.nil?
    ary.uniq
  elsif ary.empty? # The next two cases assume a non-empty array.
    []
  else
    ary.uniq do |item|
      item[property]
    rescue TypeError
      raise_property_error(property)
    rescue NoMethodError
      return nil unless item.respond_to?(:[])
      raise
    end
  end
end
upcase(input) click to toggle source

convert an input string to UPCASE

# File lib/liquid/standardfilters.rb, line 36
def upcase(input)
  input.to_s.upcase
end
url_decode(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 58
def url_decode(input)
  return if input.nil?

  result = CGI.unescape(input.to_s)
  raise Liquid::ArgumentError, "invalid byte sequence in #{result.encoding}" unless result.valid_encoding?

  result
end
url_encode(input) click to toggle source
# File lib/liquid/standardfilters.rb, line 54
def url_encode(input)
  CGI.escape(input.to_s) unless input.nil?
end
where(input, property, target_value = nil) click to toggle source

Filter the elements of an array to those with a certain property value. By default the target is any truthy value.

# File lib/liquid/standardfilters.rb, line 211
def where(input, property, target_value = nil)
  ary = InputIterator.new(input, context)

  if ary.empty?
    []
  elsif target_value.nil?
    ary.select do |item|
      item[property]
    rescue TypeError
      raise_property_error(property)
    rescue NoMethodError
      return nil unless item.respond_to?(:[])
      raise
    end
  else
    ary.select do |item|
      item[property] == target_value
    rescue TypeError
      raise_property_error(property)
    rescue NoMethodError
      return nil unless item.respond_to?(:[])
      raise
    end
  end
end

Private Instance Methods

apply_operation(input, operand, operation) click to toggle source
# File lib/liquid/standardfilters.rb, line 515
def apply_operation(input, operand, operation)
  result = Utils.to_number(input).send(operation, Utils.to_number(operand))
  result.is_a?(BigDecimal) ? result.to_f : result
end
nil_safe_casecmp(a, b) click to toggle source
# File lib/liquid/standardfilters.rb, line 534
def nil_safe_casecmp(a, b)
  if !a.nil? && !b.nil?
    a.to_s.casecmp(b.to_s)
  else
    a.nil? ? 1 : -1
  end
end
nil_safe_compare(a, b) click to toggle source
# File lib/liquid/standardfilters.rb, line 520
def nil_safe_compare(a, b)
  result = a <=> b

  if result
    result
  elsif a.nil?
    1
  elsif b.nil?
    -1
  else
    raise Liquid::ArgumentError, "cannot sort values of incompatible types"
  end
end
raise_property_error(property) click to toggle source
# File lib/liquid/standardfilters.rb, line 511
def raise_property_error(property)
  raise Liquid::ArgumentError, "cannot select the property '#{property}'"
end