Sha256: ea332522fd6b72b6d61b2d540e9208dd47530fb6bebe2a80eff515ca238f0f89

Contents?: true

Size: 1.97 KB

Versions: 4

Compression:

Stored size: 1.97 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})?/o
    ExpressionsAndOperators = /(?:\b(?:\s?and\s?|\s?or\s?)\b|(?:\s*(?!\b(?:\s?and\s?|\s?or\s?)\b)(?:#{QuotedFragment}|\S+)\s*)+)/o
    BOOLEAN_OPERATORS = %w(and or)

    def initialize(tag_name, markup, tokens)
      @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).to_s.strip

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

            new_condition = Condition.new($1, $2, $3)
            raise SyntaxError, "invalid boolean operator" unless BOOLEAN_OPERATORS.include?(operator)
            new_condition.send(operator, 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

4 entries across 4 versions & 1 rubygems

Version Path
liquid-2.6.3 lib/liquid/tags/if.rb
liquid-2.6.2 lib/liquid/tags/if.rb
liquid-2.6.1 lib/liquid/tags/if.rb
liquid-2.5.5 lib/liquid/tags/if.rb