Skip to content

Instantly share code, notes, and snippets.

@DRBragg
Created November 15, 2021 16:39
Show Gist options
  • Save DRBragg/6da0d93288899d7254e23d55253658ec to your computer and use it in GitHub Desktop.
Save DRBragg/6da0d93288899d7254e23d55253658ec to your computer and use it in GitHub Desktop.
Liquid tag to render `app/view/` erb partials in `cdk/product_templates/*/*/templates/` liquid templates
module CDK
class RenderERB < Liquid::Tag
SYNTAX = /(?<path>#{Liquid::QuotedFragment})(?<locals>\s+.*)?/
private_constant :SYNTAX
def initialize(tag_name, markup, tokens)
super
@data = SYNTAX.match(markup).named_captures
end
def render(context)
ERBRenderer.new(context, @data).render
end
class ERBRenderer
ASSIGNMENT = /(\w+):(#{Liquid::QuotedFragment})/
private_constant :ASSIGNMENT
def initialize(context, data)
@context = context
@data = data
end
def render
partial_renderer.render(partial: partial_path, locals: locals)
end
private
def partial_renderer
@partial_renderer ||= @context.registers[:action_view]
end
def partial_path
path = @data["path"] || ""
path.delete("\"")
end
def locals
@data["locals"].scan(ASSIGNMENT).each_with_object({}) do |(key, value), previous|
previous[key.to_sym] = get_variable_from_context_or_view(value)
end
end
def get_variable_from_context_or_view(lookup_key)
@context[lookup_key]
rescue NoMethodError
get_variable_from_view(lookup_key)
end
def get_variable_from_view(name)
return unless partial_renderer.instance_variable_defined?(:"@#{name}")
partial_renderer.instance_variable_get(:"@#{name}")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment