Sha256: 310c8f131c5e1668a66a86c60b46d635b925358d6f0d7b782ac0121b26371159

Contents?: true

Size: 1.54 KB

Versions: 5

Compression:

Stored size: 1.54 KB

Contents

module Locomotive
  module Liquid
    module Tags

      # Filter a collection
      #
      # Usage:
      #
      # {% with_scope main_developer: 'John Doe', active: true %}
      #   {% for project in contents.projects %}
      #     {{ project.name }}
      #   {% endfor %}
      # {% endwith_scope %}
      #

      class WithScope < ::Liquid::Block

        TagAttributes = /(\w+|\w+\.\w+)\s*\:\s*(#{::Liquid::QuotedFragment})/

        def initialize(tag_name, markup, tokens, context)
          @attributes = HashWithIndifferentAccess.new
          markup.scan(TagAttributes) do |key, value|
            key = prepare_key(key)
            @attributes[key] = value
          end
          super
        end

        def render(context)
          context.stack do
            context['with_scope'] = decode(@attributes.clone, context)
            render_all(@nodelist, context)
          end
        end

        private

        def decode(attributes, context)
          attributes.each_pair do |key, value|
            attributes[key] = context[value]
          end
        end

        def prepare_key(key)
          _key, _operator = key.split('.')

          # _slug instead of _permalink
          _key = '_slug' if _key == '_permalink'

          # key to h4s symbol
          if %w(all exists gt gte in lt lte ne nin size near within).include?(_operator)
            _key.to_s.to_sym.send(_operator.to_sym)
          else
            _key
          end
        end
      end

      ::Liquid::Template.register_tag('with_scope', WithScope)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
locomotive_cms-2.1.4 lib/locomotive/liquid/tags/with_scope.rb
locomotive_cms-2.1.3 lib/locomotive/liquid/tags/with_scope.rb
locomotive_cms-2.1.2 lib/locomotive/liquid/tags/with_scope.rb
locomotive_cms-2.1.1 lib/locomotive/liquid/tags/with_scope.rb
locomotive_cms-2.1.0 lib/locomotive/liquid/tags/with_scope.rb