scarver2 scarver2 - 15 days ago 5
Ruby Question

Liquid Standard default filter not showing default value

Given the following code:

content = "Hello {{name | default: 'Friend'}}"
Liquid::Template.parse(content).render('name' => '')


The above code should output
Hello Friend
but instead it is showing
Hello

Answer

The default filter, whilst it is in master, has not yet been released in a gem (2.6.1 is the latest gem at time of writing). Liquid’s behaviour when seeing an unknown filter seems to be to ignore it and return the string unchanged without reporting an error.

You could use the current master to get the default filter, which would be easy if you’re using Bundler, but you might not want to use unreleased code. Otherwise you could just copy it into your code until there is a release that includes it:

module MyFilters
  def default(input, default_value = "")
    is_blank = input.respond_to?(:empty?) ? input.empty? : !input
    is_blank ? default_value : input
  end
end

Liquid::Template.register_filter(MyFilters)

content = "Hello {{name | default: 'Friend'}}"
Liquid::Template.parse(content).render("name" => '')
# => "Hello Friend"
Comments