Class: Twig::TokenParser::Set

Inherits:
Base
  • Object
show all
Defined in:
lib/twig/token_parser/set.rb

Overview

Defines a variable.

{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}
{% set foo, bar = 'foo', 'bar' %}
{% set foo %}Some content{% endset %}

Instance Attribute Summary

Attributes inherited from Base

#parser

Instance Method Summary collapse

Instance Method Details

#parse(token) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/twig/token_parser/set.rb', line 14

def parse(token)
  lineno = token.lineno
  stream = parser.stream
  names = parse_assignment_expression
  capture = false

  if stream.next_if(Token::OPERATOR_TYPE, '=')
    values = parse_multi_target_expression

    stream.expect(Token::BLOCK_END_TYPE)

    if names.length != values.length
      raise Error::Syntax.new(
        'When using set, you must have the same number of variables and assignments',
        stream.current.lineno,
        stream.source
      )
    end
  else
    capture = true

    if names.length > 1
      raise Error::Syntax.new(
        'When using set with a block, you cannot have a multi-target',
        stream.current.lineno,
        stream.source
      )
    end

    stream.expect(Token::BLOCK_END_TYPE)
    values = parser.subparse(method(:decide_block_end), drop_needle: true)
    stream.expect(Token::BLOCK_END_TYPE)
  end

  Node::Set.new(capture, names, values, lineno)
end

#tagObject



51
52
53
# File 'lib/twig/token_parser/set.rb', line 51

def tag
  'set'
end