<p>You can’t access the current Twig variables (the “context”, as Twig calls them), from a Template Variable class, but you can access them with a <a href="http://buildwithcraft.com/docs/apis/templatesservice#hook" rel="noreferrer">template hook</a>.</p>

<p>From your plugin’s <code>init()</code> function:</p>

<pre><code>craft()-&gt;templates-&gt;hook('errorCheck', function(&amp;$context)
{
    if (isset($context['errors']))
    {
        // do something with $context['errors'];
    }
});
</code></pre>

<p>From your template:</p>

<pre><code>{% hook "errorCheck" %}
</code></pre>

<p>You can modify, delete, and create variables within that <code>$context</code> array if you want. And because it is passed by reference (that’s what the “<code>&amp;</code>” does in “<code>&amp;$context</code>”, you won’t need to actually return the array at the end of the function or anything; just make your changes to it.</p>

CC BY-SA 3.0
2014-10-05T16:00:23.400Z
Thanks Brandon.  It took me a bit to contemplate this and my options to allow the user to only have one tag in the template. I've posted the solution I found to work best below. This is a handy method, and I appreciate the clarification on passing a variable by reference.
Ben Parizek
CC BY-SA 3.0
2015-11-19T00:39:30.483Z
Should I be able to use this method to retrieve twig variables that are set by a user in the template? e.g. `{% set myThing = "foo" %}` with `$context["myThing"]`
cmal
CC BY-SA 3.0
2015-11-22T21:18:35.813Z
@cmal Yes - anything that is defined at the time the `{% hook %}` tag is called will be available to your plugin.
Brandon Kelly
CC BY-SA 3.0
2014-07-25T17:12:05.910Z
2014-07-25T17:12:05.910Z
Brandon Kelly
<p>I ended up solving this by creating a public variable in my service layer and assigning and retrieving the submitted object from there.  This helps me keep any new error handling specific code out of the templates for the users, and the output tag can now handle both submitting and error handling in the form.</p>

<p>This method has three parts:</p>

<ol>
<li>Public variable in the service layer that handles the submitted Form object (this gets set after the submission is validated and gets retrieved, if it exists, when the tag is processed.</li>
<li>Controller that handles the Form submission</li>
<li>Variable in the template file<br>
<code>craft.sproutForms.outputForm()</code></li>
</ol>

<p>More specifically, our service layer has a public variable:</p>

<p><code>public $activeEntry;</code></p>

<p>If our submission fails, we assign the submitted object with errors to the <code>$activeEntry</code> variable:</p>

<pre><code>if (craft()-&gt;myPlugin-&gt;saveEntry($entry)) 
{
   ...
}
else
{
   craft()-&gt;myPlugin-&gt;activeEntry = $entry;

   ...
}
</code></pre>

<p>And, when the page loads and the <code>outputForm()</code> tag is processed, we check to see if that <code>$activeEntry</code> variable is set.</p>

<pre><code>if (isset(craft()-&gt;myPlugin-&gt;activeEntry))
{
    $entry = craft()-&gt;myPlugin-&gt;activeEntry;    
}
else
{
    $entry = new MyPlugin_EntryModel();
}
</code></pre>

CC BY-SA 3.0
2014-10-05T15:56:28.267Z
2014-10-05T15:56:28.267Z
Ben Parizek
<p>I have a controller that returns route variables to the page:</p>

<pre><code>craft()-&gt;urlManager-&gt;setRouteVariables(array(
  'errors' =&gt; $entry-&gt;getErrors()
));
</code></pre>

<p>On the page that gets loaded, I can access the variables I set in the template:</p>

<pre><code>{% for error in errors %} ...
</code></pre>

<p>However, I want to handle this variable dynamically. Is it possible to access the 'errors' variable in my MyPluginVariable.php file without passing it directly to my variable function? </p>

<p>I don't want to do this:</p>

<pre><code>{{ craft.myPlugin.doSomething(errors) }}
</code></pre>

<p>That passes my variable to the plugin variable and I can access it just fine.  But I don't want to ask the user to pass this variable to the function every time, I'd prefer to just handle it in the background.</p>

<p>So, on the page that gets loaded, instead of outputting the variable, can I have a Twig tag like this:</p>

<pre><code>{{ craft.myPlugin.doSomething() }}
</code></pre>

<p>And directly access the 'errors' variable in my plugin?  Something like (this doesn't work):</p>

<pre><code>craft()-&gt;request-&gt;getRouteVariables('errors')
</code></pre>

CC BY-SA 3.0
2014-07-12T17:19:39.827Z
Why don't you do any of your dynamic error processing in your plugin's controller before you return it to the template?
Brad Bell
CC BY-SA 3.0
2014-07-12T17:31:49.447Z
Maybe I'm missing something.  My tag outputs a Form: `craft.myPlugin.outputForm()` with a single line, so the data I'm getting back is a bunch of stuff that that tag needs to output.  When the form is created, the tag just needs to point at the form handle to get all the info it needs `craft.myPlugin.outputForm('handle')` but if things don't validate, the page reloads and I have an object of submitted values that need to maintain state and errors and I was just wondering if I could avoid doing something like `craft.myPlugin.outputForm('handle', values, errors)`
Ben Parizek
<plugin-development><templating><routes>
Is it possible to access Twig variables in a plugin variable using PHP?
# Is it possible to access Twig variables in a plugin variable using PHP?

(Asked by: username_0 on 2014-07-12)

I have a controller that returns route variables to the page:
craft()->urlManager->setRouteVariables(array(
  'errors' => $entry->getErrors()
));

On the page that gets loaded, I can access the variables I set in the template:
{% for error in errors %} ...

However, I want to handle this variable dynamically. Is it possible to access the 'errors' variable in my MyPluginVariable.php file without passing it directly to my variable function? 
I don't want to do this:
{{ craft.myPlugin.doSomething(errors) }}

That passes my variable to the plugin variable and I can access it just fine.  But I don't want to ask the user to pass this variable to the function every time, I'd prefer to just handle it in the background.
So, on the page that gets loaded, instead of outputting the variable, can I have a Twig tag like this:
{{ craft.myPlugin.doSomething() }}

And directly access the 'errors' variable in my plugin?  Something like (this doesn't work):
craft()->request->getRouteVariables('errors')

**Tags:** plugin-development, templating, routes

> **Comments:**
> **username_1**: Why don't you do any of your dynamic error processing in your plugin's controller before you return it to the template?  
> **username_0**: Maybe I'm missing something.  My tag outputs a Form: `craft.myPlugin.outputForm()` with a single line, so the data I'm getting back is a bunch of stuff that that tag needs to output.  When the form is created, the tag just needs to point at the form handle to get all the info it needs `craft.myPlugin.outputForm('handle')` but if things don't validate, the page reloads and I have an object of submitted values that need to maintain state and errors and I was just wondering if I could avoid doing something like `craft.myPlugin.outputForm('handle', values, errors)`  

---

## 2 answers

### Answer by username_2 on 2014-07-25. Score: 5

You can’t access the current Twig variables (the “context”, as Twig calls them), from a Template Variable class, but you can access them with a template hook.
From your plugin’s init() function:
craft()->templates->hook('errorCheck', function(&$context)
{
    if (isset($context['errors']))
    {
        // do something with $context['errors'];
    }
});

From your template:
{% hook "errorCheck" %}

You can modify, delete, and create variables within that $context array if you want. And because it is passed by reference (that’s what the “&” does in “&$context”, you won’t need to actually return the array at the end of the function or anything; just make your changes to it.

> **Comments:**
> **username_0**: Thanks Brandon.  It took me a bit to contemplate this and my options to allow the user to only have one tag in the template. I've posted the solution I found to work best below. This is a handy method, and I appreciate the clarification on passing a variable by reference.  
> **username_3**: Should I be able to use this method to retrieve twig variables that are set by a user in the template? e.g. `{% set myThing = "foo" %}` with `$context["myThing"]`  
> **username_2**: @username_3 Yes - anything that is defined at the time the `{% hook %}` tag is called will be available to your plugin.  

---

### Answer by username_0 on 2014-10-05. Score: 2

I ended up solving this by creating a public variable in my service layer and assigning and retrieving the submitted object from there.  This helps me keep any new error handling specific code out of the templates for the users, and the output tag can now handle both submitting and error handling in the form.
This method has three parts:

Public variable in the service layer that handles the submitted Form object (this gets set after the submission is validated and gets retrieved, if it exists, when the tag is processed.
Controller that handles the Form submission
Variable in the template file
craft.sproutForms.outputForm()

More specifically, our service layer has a public variable:
public $activeEntry;
If our submission fails, we assign the submitted object with errors to the $activeEntry variable:
if (craft()->myPlugin->saveEntry($entry)) 
{
   ...
}
else
{
   craft()->myPlugin->activeEntry = $entry;

   ...
}

And, when the page loads and the outputForm() tag is processed, we check to see if that $activeEntry variable is set.
if (isset(craft()->myPlugin->activeEntry))
{
    $entry = craft()->myPlugin->activeEntry;    
}
else
{
    $entry = new MyPlugin_EntryModel();
}


---

