I'm having something in my mind that need to be implemented in the current project. I'll explain with a example below:
I will be having below variables structure used in a lot of templates:
{% if article.tags is iterable %}
{% for tag in article.tags %}
{{ tag.title }}
{% endfor %}
{% endif %}
As you can see at the #1 line above, i will then assign "article" variable data that having a list of "tags" data from PHP to the Twig template loader, in common usage. But, I don't want to load the "tags" data from database and assign to the template, because i think it will use my server connection and resource even the "tags" data used or not.
So i think the best approach is to using event listener (hook) concept, implemented inside the Twig, below is the process:
1) I'm preparing a listener at somewhere in my PHP file before the template loaded: $this->twig->addListenerMethod($this, 'tags');
2) When the Twig parse the "tags" variable, it will check if there are a listener that having the same method name attached to the variable.
3) When listeners found, the Twig will call the method specified by passing the parent object (article) as it first parameter.
4) When the method called, it will process as it should and return the "tags" data list needed.
My question are:
1) In which Twig source file that I can start to look and implement the event listener (hook) concept in Twig?
2) Is there someone already having the same implementation using Twig as i described above?
3) or somebody having some suggestions?
I wish i can have a lot of suggestions about this, while i'm digging into the Twig source also.
Thanks.
Kind regards.
I have found the solution for my own question:
I just need to assign a "Article" object to the template:
Below is how the object "Article" look like:
And if you want to pass and arguments to the method "tags", just use below example: