Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Liquid Standard default filter not showing default value

Tags:

ruby

liquid

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

like image 317
scarver2 Avatar asked Mar 07 '26 14:03

scarver2


1 Answers

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"
like image 55
matt Avatar answered Mar 09 '26 04:03

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!