2

I'm trying to update the context from within a macro. Is this possible at all? I'm pretty close with the below code.

The var_dump within the below function shows the updated context. But when doing a {{ dump(_context|keys) }} after the macro call the context is unchanged.

Any ideas, much appreciated.

<?php
namespace Craft;

class TwiggedTwigExtension extends \Twig_Extension
{
  public function getName()
  {
    return 'Twigged';
  }

  public function getFunctions()
  {
    return array(
      'addVar' => new \Twig_SimpleFunction('addVar', array($this, 'addVar'), array('needs_context' => true)),
    );
  }

  public function addVar($context, $str, $val)
  {
    $context['context'][$str] = $val;
    var_dump(array_keys($context['context']));
  }
}
  • Are you referring to a macro as defined with {% macro %} or this custom Twig Extension? If you're referring to an extension, I recommend going to StackOverflow as they will have more twig-related answers than we will. – Bryan Redeagle Sep 11 '15 at 13:20
  • Even calling the function in the template without the macro like so {{ addVar('hello', 'world') }} results in the same. I have also tried passing context by reference. – Fyrebase Sep 11 '15 at 13:35
2

So I took another approach to my problem and ended up creating a plugin variable allowing me to set data inside a macro and have it accessible in the template. It's not complicated and does the trick.

class MyPluginVariable
{
  /**
   * Store data for use within both
   * templates and macros. Easy way around
   * macros having their own context
   * @var [Array]
   */
  private static $store = [];

  /**
   * Set data in storage array
   * @param [String] $key
   * @param $value
   */
  public function set($key, $value) {
    self::$store[$key] = $value;
  }

  /**
   * Retrieve data from storage array
   * @param  [String] $key
   */
  public function get($key) {
    return self::$store[$key];
  }
}

To set data you simply call {% do craft.MyPlugin.set('myVar', true) %} and to retrieve it {% set myVar = craft.MyPlugin.get('myVar') %}

1

From a quick glance, I don't think this is possible. In that function, the context is being passed in by value, not reference... So any changes are only to the local scope.

  • Thanks @jeremy. I've also tried passing it in by reference with the same result. – Fyrebase Sep 12 '15 at 3: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.