timber / starter-theme

The "_s" for Timber: a dead-simple theme that you can build anything from
MIT License
817 stars 276 forks source link

Ability to register twig namespaces? #42

Closed jesconstantine closed 9 months ago

jesconstantine commented 7 years ago

Are there any plans allow twig namespace registers? This is built-in twig functionality, see: http://twig.sensiolabs.org/doc/2.x/api.html#loaders

These namespaces would allow, for example, pattern lab twig templates to be imported via a composer and used as is, with data being passed to them in Timber context.

So a twig include statement could use something like @atoms/headings/comp-heading.twig where @atoms is namespaced to a path like /views/patterns/atoms.

Apologies if this functionality exists and I've missed it, I've only read through the Timber docs once.

jarednova commented 7 years ago

@jesconstantine thanks for the suggestion! The only thing I know is that namespaces aren't formally supported — but it doesn't mean they shouldn't be. If this is something you could investigate I'd love to see a PR here or to Timber so we can add that functionality

matt416 commented 6 years ago

It's possible to use namespaces by hooking onto the timber/loader/loader filter.

In your functions.php (or plugin) add

add_filter('timber/loader/loader', function($loader){
    $loader->addPath(__DIR__ . "/views/components", "components");
    return $loader;
});

$loader is an instance of Twig_Loader_Filesystem. addPath is one of it's methods, requiring the full path, and an optional namespace as params.

To use the namespace in your Twig template, just include it with an @ prefix

{{ include('@components/filename.twig') }}
ThomasBerends commented 6 years ago

@jarednova @matt416 Can confirm this solution works. I'm using this now to separate some common templates from our themes and in a common plugin so we can update this separately.