Sha256: 37a2508354ecef5e5ff027345fbf472de0aab6df9846ab495b55721a01af1c0e

Contents?: true

Size: 1.99 KB

Versions: 1

Compression:

Stored size: 1.99 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 = /(?:and|or|(?:\s*(?!\b(?:and|or)\b)(?:#{QuotedFragment}|\S+)\s*)+)/
    
    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 
          
          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
liquid-2.1.0 lib/liquid/tags/if.rb