Sha256: db6513bb2e0875404fc629ae830733bf64c01a9597dc78f32192463f886a4baa

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

module Liquid

  # If is the conditional block
  #
  #   {% if user.admin %}
  #     Admin user!
  #   {% else %}
  #     Not admin user
  #   {% endif %}
  #
  #    There are {% if count < 5 %} less {% else %} more {% endif %} items than you need.
  #
  #
  class If < Block
    SyntaxHelp = "Syntax Error in tag 'if' - Valid syntax: if [expression]"
    Syntax = /(#{QuotedFragment})\s*([=!<>a-z_]+)?\s*(#{QuotedFragment})?/
    ExpressionsAndOperators = /(?:\b(?:and|or)\b|(?:\s*(?!\b(?:and|or)\b)(?:#{QuotedFragment}|\S+)\s*)+)/

    def initialize(tag_name, markup, tokens, context)

      @blocks = []

      push_block('if', markup)

      super
    end

    def unknown_tag(tag, markup, tokens)
      if ['elsif', 'else'].include?(tag)
        push_block(tag, markup)
      else
        super
      end
    end

    def render(context)
      context.stack do
        @blocks.each do |block|
          if block.evaluate(context)
            return render_all(block.attachment, context)
          end
        end
        ''
      end
    end

    private

    def push_block(tag, markup)
      block = if tag == 'else'
        ElseCondition.new
      else

        expressions = markup.scan(ExpressionsAndOperators).reverse
        raise(SyntaxError, SyntaxHelp) unless expressions.shift =~ Syntax

        condition = Condition.new($1, $2, $3)

        while not expressions.empty?
          operator = expressions.shift

          raise(SyntaxError, SyntaxHelp) unless expressions.shift.to_s =~ Syntax

          new_condition = Condition.new($1, $2, $3)
          new_condition.send(operator.to_sym, condition)
          condition = new_condition
        end

        condition
      end

      @blocks.push(block)
      @nodelist = block.attach(Array.new)
    end


  end

  Template.register_tag('if', If)
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
locomotive_liquid-2.1.3 lib/liquid/tags/if.rb