Sha256: ac264c5b77b54d3b76067d3d583aee69ebc2d85a497b90ea6bf74f26d93234ad

Contents?: true

Size: 1.23 KB

Versions: 6

Compression:

Stored size: 1.23 KB

Contents

module Liquid
  # Assign sets a variable in your template.
  #
  #   {% assign foo = 'monkey' %}
  #
  # You can then use the variable later in the page.
  #
  #  {{ foo }}
  #
  class Assign < Tag
    Syntax = /(#{VariableSignature}+)\s*=\s*(.*)\s*/om

    attr_reader :to, :from

    def initialize(tag_name, markup, options)
      super
      if markup =~ Syntax
        @to = $1
        @from = Variable.new($2, options)
      else
        raise SyntaxError.new options[:locale].t("errors.syntax.assign".freeze)
      end
    end

    def render(context)
      val = @from.render(context)
      context.scopes.last[@to] = val
      context.resource_limits.assign_score += assign_score_of(val)
      ''.freeze
    end

    def blank?
      true
    end

    private

    def assign_score_of(val)
      if val.instance_of?(String)
        val.length
      elsif val.instance_of?(Array) || val.instance_of?(Hash)
        sum = 1
        # Uses #each to avoid extra allocations.
        val.each { |child| sum += assign_score_of(child) }
        sum
      else
        1
      end
    end

    class ParseTreeVisitor < Liquid::ParseTreeVisitor
      def children
        [@node.from]
      end
    end
  end

  Template.register_tag('assign'.freeze, Assign)
end

Version data entries

6 entries across 6 versions & 3 rubygems

Version Path
liquid-4.0.4 lib/liquid/tags/assign.rb
metanorma-cli-1.3.4 gems/ruby/2.6.0/gems/liquid-4.0.3/lib/liquid/tags/assign.rb
metanorma-cli-1.3.3.1 gems/ruby/2.6.0/gems/liquid-4.0.3/lib/liquid/tags/assign.rb
liquid-4.0.3 lib/liquid/tags/assign.rb
liquid-4.0.2 lib/liquid/tags/assign.rb
liquid-4-0-2-4.0.2 lib/liquid/tags/assign.rb