vaersaagod/seomate

How to handle the removal of globals?

Closed this issue ยท 5 comments

Craft is moving away from Globals. We preemptively did that for one of our sites but it broke our fallbacks... (we use an SeoDefaults global to set default fallbacks)... any way around that?

The 'defaultMeta' setting works with any object in your global Twig context, so your "SeoDefaults" doesn't necessarily have to be a global set (globals are just convenient to use because they're... global ๐Ÿ™ƒ).

In other words, to use a single entry for the default meta, you have to make sure it's in your global Twig context (the below example assumes you have something like 'defaultSeo.seoTitle' etc in your default meta config):

{% set defaultSeo = craft.entries.section('defaultSeo').one() %}

{% hook 'seomateMeta' %}

...pretty awkward stuff. Things will probably change in SEOMate once global sets are actually removed from core (probably Craft 5.0), but I'm reluctant to refactor anything until then, i.e. for Craft 4 global sets are still the recommended thing to use for defaultMeta.

Oh! I see - that's not bad. I can put that in my base layout template. Thank you!

@mmikkel I stumbled across the same problem. There is the preloadSingles setting. If this is set to true, singles can be used via their handle in the same way as globals.

However, this does not work with defaultMeta, presumably because the singles do not appear in the _context of Twig. However, it is not entirely clear to me why. Any idea why this is the case?

@mihob It's a limitation due to how the preloadSingles feature is implemented. SEOMate works by looking at the global Twig context via a template hook (i.e. from PHP). The problem is that preloaded singles are never actually added to the Twig context; instead they are essentially swapped in as fallback values, for any undefined template variable that happens to match a preloaded single's handle. This all happens in the Twig layer during template rendering, and since the context isn't changed as a result, PHP code running in a template hook has no way to know about it.

Technically though, you can use a preloaded single for SEOMate's meta by explicitly setting it to a variable (because that variable will be in the context):

{% set defaultSeo = defaultSeo|default %}

{% hook 'seomateMeta' %}

Compared to the solution I gave @mattbloomfield above, I'd probably rate this even higher on the awkward scale, but it will potentially save you 1 query.

As stated we'll likely make some changes regarding this in SEOMate for Craft 5, but for Craft 4 our recommendation is to keep using global sets for the meta data.

Update: Global sets weren't removed in Craft 5 after-all, so everything above is still relevant for SEOMate 3.x for Craft 5 :)