I'm writing a plugin which has a hook like:

craft()->templates->hook('myHook', function(&$context)
    return array('hello', 'there');

While I can call it in a template with:

{% hook myHook %}

I get an "Array to string conversion", understandably. But I can't work out how to treat the returned data like an array. How can I use hook 'myHook' in a for loop, or set it to a variable? It must be simple, but I've exhausted my random attempts.

  • I'm now thinking maybe I should be using a Variable for this instead. I'm not sure what the pros/cons are of either method. Jun 26 '15 at 13:16

Template hooks are useful if you need to change the current twig context array somewhere inside of a template. If you make any changes to $context inside of your hook's function, those changes will be available after your hook tag.

If you just need to return some text or an array, a variable will do the trick just fine!

  • Gotcha, thanks Aaron. Yes, variables seem to do the trick and be a much better solution. It wasn't quite clear from things I've read what the purpose of hooks were, and I went up the wrong path. Jun 26 '15 at 14:34

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.