1

I am using this SO post to try to concatenate two variables in twig.

I am very close, but can't seem to get over the hump of rendering the correct syntax.

This is what I am currently using:

 {% for user in plugin.data.users %}
     ...  
     {{ attribute(user, 'foo' ~ loop.index0)|raw|nl2br.bar }}
     ...
 {% endfor %}

This is what I am currently getting back:

Key "foo0"... for array with keys "...does not exist."

What I am trying to create is foo[0], foo[1] etc.

Well, I couldn't figure it out so this is how I did it. If there is a better way, I'd be happy to update the post.

{% set i = 0 %}
    {{ user.foo[i].bar }}
    ...
{% set i = i + 1 %}
1

I think you need to try and access the array that user.foo would have. So your code would be something like:

 {% for user in plugin.data.users %}
  ...  
  {{ attribute(user.foo, loop.index0)|raw|nl2br }}
  ...
 {% endfor %}

I haven't tested this though, just going by what I'm sure I remember doing once...

  • Thanks @Alec, I couldn't get it figured out using the attribute tag. I updated my question with how I got it to work. – Damon Jan 10 '17 at 0:54
1

I've gotten a bit further into this that is slightly beyond the scope of my original question, but I think it's worth bringing up for the benefit of others (like me).

To answer my original question, this is how I was able to make it work:

{% set i = 0 %}
    {{ user.foo[i].bar }}
    ...
{% set i = i + 1 %}

However, if your templates start to become more complex, and/or need more or different types of looping, you might want to consider looking at a template hook

This works pretty slick. Let's say I am getting data from an api or some other service (using a plugin). This is how you would use a hook.

template.twig

...
{% hook 'myAwesomeHook' %}

Since it is recommended to place the hook logic in the init method of your plugin, this is what that would look like:

MyPlugin.php

...
public function init() {
    craft->template()->hook('myAwesomeHook', function(&$context) {
       foreach($context['user'] as $user) {
         return $user; // or do whatever you need.
       }
    }
}

Hope this helps someone else!

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.