2

There are three methods for that:

object.attribute
object['attribute']
attr(object, 'attribute')

How are these different from each other?

Piotr Pogorzelski
  • 1,286
  • 7
  • 18

1 Answers1

4
    {{ entry.title }}

compiles down to:

        echo twig_escape_filter($this->env, craft\helpers\Template::attribute($this->env, $this->source, (isset($context["entry"]) || array_key_exists("entry", $context) ? $context["entry"] : (function () { throw new RuntimeError('Variable "entry" does not exist.', 19, $this->source); })()), "title", []), "html", null, true);

...and

    {{ entry['title'] }}

compiles down to:

        echo twig_escape_filter($this->env, craft\helpers\Template::attribute($this->env, $this->source, (isset($context["entry"]) || array_key_exists("entry", $context) ? $context["entry"] : (function () { throw new RuntimeError('Variable "entry" does not exist.', 20, $this->source); })()), "title"), "html", null, true);

...and

    {{ attribute(entry, 'title') }}

compiles down to:

        echo twig_escape_filter($this->env, craft\helpers\Template::attribute($this->env, $this->source, (isset($context["entry"]) || array_key_exists("entry", $context) ? $context["entry"] : (function () { throw new RuntimeError('Variable "entry" does not exist.', 21, $this->source); })()), "title", [], "array"), "html", null, true);

If they look similar, that's because... they are identical in terms of the PHP code they compile down to.

So the difference is... whichever one uses the fewest keystrokes to type.

andrew.welch
  • 11,551
  • 22
  • 31
  • There seems to hovewer be some difference - for non existing field, entry.dwfgfrg is defined returns true, but entry['dwfgfrg'] is defined returns false. – Piotr Pogorzelski Mar 04 '21 at 17:23
  • 1
    Check out Ben Parizek's answer in this thread: https://craftcms.stackexchange.com/questions/2116/twig-is-defined-always-returning-true – andrew.welch Mar 05 '21 at 15:41
  • 1
    They will definitely throw different errors in different circumstances. You may want to conduct the same test, but where entry is properly defined, and it's only the attribute that is missing. – Lindsey D Mar 05 '21 at 17:50
  • The difference here is in how the "is defined" test works tho, now how the various ways of accessing properties works. Ben gives a really good explanation in the above link – andrew.welch Mar 06 '21 at 18:11