starter-theme icon indicating copy to clipboard operation
starter-theme copied to clipboard

Ability to register twig namespaces?

Open jesconstantine opened this issue 8 years ago • 3 comments

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.

jesconstantine avatar Mar 07 '17 13:03 jesconstantine

@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

jarednova avatar Mar 07 '17 14:03 jarednova

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') }}

matt416 avatar Oct 05 '17 15:10 matt416

@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.

ThomasBerends avatar Oct 13 '17 20:10 ThomasBerends