FORSMILE
JA
Twig2021/02/04

[Twig] Displaying Arrays & Calling Methods (attribute function)

An introduction to how to use Twig's `attribute` function.

Back to Blog

This is an introduction to how to use Twig's `attribute` function.

Official documentation: https://twig.symfony.com/doc/3.x/functions/attribute.html

CALLING METHODS USING ATTRIBUTE

css
{{ attribute(object, method) }}
{{ attribute(object, method, arguments) }}

How to use attribute: Example

javascript
// make sample function
{% macro foo(name, age) %}
      NAME:{{ name }}
      AGE:{{ age }}
{% endmacro %}

// attribute
{{ attribute(_self, 'foo', ['Mishima', 33]) }}

// result
NAME:Mishima AGE:33

As a side note, since we created this function as a macro this time, it can also be called using the following.

css
{{ _self.foo('Mishima', 33) }}

DISPLAYING ARRAY CONTENTS WITH ATTRIBUTE

If an array key is unconventional, there is a way to retrieve its value using `attribute`.

(For example, characters like '-' would be treated as a subtraction operator.)

css
{{ attribute(foo, 'data-foo') }}

// cant use
{{ foo.data-foo }}

RECOMMENDED TWIG BOOKS

I haven't read any books specifically dedicated to Twig, but I found one on Amazon Kindle.

📦
Amazon で関連書籍・ツールを検索
PHP Twig template engine
Amazonで探す →(アソシエイトリンク)