Shopify / liquid

Liquid markup language. Safe, customer facing template language for flexible web apps.
https://shopify.github.io/liquid/
MIT License
11.13k stars 1.39k forks source link

Custom Liquid::Drop that is called for every missing variable #1780

Closed 23tux closed 10 months ago

23tux commented 10 months ago

Hi everyone,

I'm fairly new to liquid, and I'm wondering if my use case is possible: Is it possible to have a custom drop that is called whenever a variable is unknown in a template?

class FallbackDrop < Liquid::Drop
  def liquid_method_missing(method_name)
    # lookup value in a database or something
    "fallback value"
  end
end

drop = FallbackDrop.new
template = Liquid::Template.parse("drop via key '{{ fallback.unknown }}'; drop without key '{{ unknown }}'")
puts template.render("fallback" => drop)

=> drop via key 'fallback value'; drop without key ''

I want somehow to be able to invoke the drop when {{ unknown }} is rendered. Is this possible using liquid_method_missing? Can I somehow register a drop as the fallback if something is missing? Or is Liquid::Drop the wrong way of doing this and a, I don't know, custom Liquid::Context is the way of doing such a thing?

Thanks!

23tux commented 10 months ago

Nevermind, I found out that you can just pass the drop instance directly into the render call:

class FallbackDrop < Liquid::Drop
  def liquid_method_missing(method_name)
    # lookup value in a database or something
    "fallback value"
  end
end

drop = FallbackDrop.new
template = Liquid::Template.parse("drop without key '{{ unknown }}'")
puts template.render(drop)
=> drop without key 'fallback value'