Multiple Template Variables in Plugin Development
Problem
You want your plugin to have multiple template variables.
Solution
Use PHP’s overloading in the main template variable to load in separate template variables.
Assuming that your plugin was named CocktailRecipes
, your CocktailRecipesVariable.php
file would look like this:
<?php
namespace Craft;
class CocktailRecipesVariable
{
public function __call($name, $arguments)
{
$className = 'Craft\CocktailRecipes_' . ucfirst($name) . 'Variable';
return (class_exists($className)) ? new $className() : null;
}
}
Your extracted CocktailRecipes_IngredientsVariable.php
variable file would look like this:
<?php
namespace Craft;
class CocktailRecipes_IngredientsVariable
{
public function getAll()
{
// Some code to get all ingredients
}
}
And then your template would look like this:
{% for ingredient in craft.cocktailRecipes.ingredients.getAll %}
{# Do something with the ingredient #}
{% endfor %}
Discussion
This can be useful when you have a complicated plugin that has multiple services and controllers, and you want to keep your variables associated with your services.
Submitted by Ben Wilkins on 1st February, 2017