Sha256: bdbfcd86fd25cf2943840fe4c8917a6279cf0ef135f7d5dc18accef7fde93b92

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

module Slim
  # Perform interpolation of #{var_name} in the
  # expressions `[:slim, :interpolate, string]`.
  #
  # @api private
  class Interpolation < Filter
    # Handle interpolate expression `[:slim, :interpolate, string]`
    #
    # @param [String] string Static interpolate
    # @return [Array] Compiled temple expression
    def on_slim_interpolate(string)
      # Interpolate variables in text (#{variable}).
      # Split the text into multiple dynamic and static parts.
      block = [:multi]
      until string.empty?
        case string
        when /^\\#\{/
          # Escaped interpolation
          block << [:static, '#{']
          string = $'
        when /^#\{/
          # Interpolation
          string, code = parse_expression($')
          escape = code !~ /^\{.*\}$/
          block << [:escape, escape, [:dynamic, escape ? code : code[1..-2]]]
        when /^([^#]+|#)/
          # Static text
          block << [:static, $&]
          string = $'
        end
      end
      block
    end

    protected

    def parse_expression(string)
      stack, code = [], ''

      until string.empty?
        if stack.empty? && string =~ /^\}/
          # Stack is empty, this means we are finished
          # if the next character is a closing bracket
          string.slice!(0)
          break
        elsif string =~ Parser::DELIMITER_REGEX
          # Delimiter found, push it on the stack
          stack << Parser::DELIMITERS[$&]
          code << string.slice!(0)
        elsif string =~ Parser::CLOSE_DELIMITER_REGEX
          # Closing delimiter found, pop it from the stack if everything is ok
          raise "Text interpolation: Unexpected closing #{$&}" if stack.empty?
          raise "Text interpolation: Expected closing #{stack.last}" if stack.last != $&
          code << string.slice!(0)
          stack.pop
        else
          code << string.slice!(0)
        end
      end

      return string, code
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
slim-0.9.3 lib/slim/interpolation.rb