Class: Twig::TokenParser::Use

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

Overview

Imports blocks defined in another template into the current template.

extends “base.html” % use “blocks.html” %

block title %endblock %

Instance Attribute Summary

Attributes inherited from Base

#parser

Instance Method Summary collapse

Instance Method Details

#parse(token) ⇒ Object



12
13
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
# File 'lib/twig/token_parser/use.rb', line 12

def parse(token)
  template = parser.parse_expression
  stream = parser.stream

  unless template.is_a?(Node::Expression::Constant)
    raise Error::Syntax.new(
      'The template references in a "use" statement must be a string.',
      stream.current.lineno,
      stream.source
    )
  end

  targets = {}

  if stream.next_if('with')
    loop do
      aliased = name = stream.expect(Token::NAME_TYPE).value

      if stream.next_if('as')
        aliased = stream.expect(Token::NAME_TYPE).value
      end

      targets[name] = Node::Expression::Constant.new(aliased, -1)

      unless stream.next_if(Token::PUNCTUATION_TYPE, ',')
        break
      end
    end
  end

  stream.expect(Token::BLOCK_END_TYPE)

  parser.add_trait(Node::Nodes.new({ template:, targets: Node::Nodes.new(targets) }))

  Node::Empty.new(token.lineno)
end

#tagObject



49
50
51
# File 'lib/twig/token_parser/use.rb', line 49

def tag
  'use'
end