2

Is there a particular school of thought on which is best to use?

They both appear to offer the same thing - exposing data and functionality to templates.

4

The following answer is all personal opinion of course, but here's a key quote from the docs:

Many of your template variable methods will likely be simple wrappers for your service API methods.

If you look at Craft's built-in Variables, they're all about exposing data. Personally, I like to think of Variables as template APIs.

Twig Filters, on the other hand, is all about modifying data (e.g. capitalizing strings, rounding numbers, formatting dates, sorting arrays etc). If you compare Craft's built-in Variables to its Filters, I think the distinction between the two starts to become fairly clear.

To exemplify:

Bad use of Variables:

{% set sortedEntries = craft.myPlugin.sortByAwesomeLevel( entries ) %}
{{ craft.myPlugin.makeEntryTitleAwesome( entry.title ) }}

The above template code use Variable methods to modify data already present in the template. It works, but it looks pretty convoluted and doesn't really make sense, neither from a Twig nor Craft point of view. Here, using Filters would be much more appropriate:

{% set sortedEntries = entries | sortBy( 'awesomeLevel' ) %}
{{ entry.title | makeAwesome }}

Good use of Variables:

{% set awesomeEntries = craft.myPlugin.getAwesomeEntries %}
{% set sortedAwesomeEntries = craft.myPlugin.getAwesomeEntries( { 'sortBy' : 'awesomeLevel' } ) %}

Here, MyPlugin exposes a "template API" method called getAwesomeEntries. The only thing it does, is to pull entries that are awesome, optionally taking an arguments object for sorting or the like. Obviously, this would not be feasible to implement as a Filter:

{% set awesomeEntries = entries | getAwesomeEntries %}

In short – if you need to expose data, use a Variable. If you need to modify data, use Filters.

2

I'd say; use twig functions/filters when the data you want to operate on comes from your template, plugin variables when you need to operate on data from your plugin/another source.

You can, to my knowledge, do the exact same things with both. But the purpose of twig filters is to manipulate data in your templates. If the filter relies on tapping into Craft to work, I'd rethink using one.

But that's just my opinion, I don't think there's been a lot of discussion about this in the community. :)

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.