1

There are three methods for that:

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

How are these different from each other?

3
    {{ 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.

4
  • There seems to hovewer be some difference - for non existing field, entry.dwfgfrg is defined returns true, but entry['dwfgfrg'] is defined returns false.
    – piotrpog
    Mar 4 at 17:23
  • 1
    Check out Ben Parizek's answer in this thread: craftcms.stackexchange.com/questions/2116/… Mar 5 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 5 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 Mar 6 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.