Class: Twig::Node::Expression::Name

Inherits:
Base
  • Object
show all
Includes:
SupportDefinedTest
Defined in:
lib/twig/node/expression/name.rb

Direct Known Subclasses

AssignName, Variable::Context

Constant Summary collapse

SPECIAL_VARS =
{
  '_self' => 'template_name',
  '_context' => 'context',
  '_charset' => 'env.charset',
}.freeze

Instance Attribute Summary

Attributes inherited from Base

#attributes, #lineno, #nodes, #source_context, #tag

Instance Method Summary collapse

Methods included from SupportDefinedTest

#define_test_enabled?, #enable_defined_test

Methods inherited from Base

#explicit_parentheses?, #set_explicit_parentheses

Methods inherited from Base

#empty?, #length, #template_name, #to_s

Constructor Details

#initialize(name, lineno) ⇒ Name

Returns a new instance of Name.

Parameters:

  • name (String)
  • lineno (Integer)


19
20
21
22
23
24
25
26
# File 'lib/twig/node/expression/name.rb', line 19

def initialize(name, lineno)
  super({}, {
    name:,
    is_defined_test: false,
    ignore_strict_check: false,
    always_defined: false,
  }, lineno)
end

Instance Method Details

#compile(compiler) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/twig/node/expression/name.rb', line 28

def compile(compiler)
  name = attributes[:name]

  compiler.add_debug_info(self)

  check = "context.has?(:#{name})"
  get = "context.get(:#{name})"

  if define_test_enabled?
    if attributes[:always_defined] || SPECIAL_VARS.key?(name)
      compiler.repr(true)
    else
      compiler.raw(check)
    end
  elsif SPECIAL_VARS.key?(name)
    compiler.raw(SPECIAL_VARS[name])
  elsif attributes[:always_defined]
    compiler.
      raw(get)
  elsif attributes[:ignore_strict_check] || !compiler.environment.strict_variables?
    compiler.
      raw('(').
      raw(get).
      raw(' || nil)')
  else
    compiler.
      raw("(#{check}").
      raw(" ? #{get}").
      raw(' : raise(::Twig::Error::Runtime.new("Variable \"#{').
      string(name).
      raw('}\" does not exist.", ').
      repr(lineno).
      raw(', source_context)))')
  end
end