I'm upgrading a legacy site from Craft 2 to Craft 3.
It's very much one-error-at-a-time and I'm stuck currently at a particular component's template file.
I have this legacy code:
{% set componentLocale = componentLocale is defined ? componentLocale : '' %}
{% set myGlobal = componentLocale ? myGlobal.locale(componentLocale) : myGlobal %}
{% if myGlobal is defined and myGlobal.myGlobalTitle is not empty %}
... HTML for component
{% endif %}
If I understand it correctly, it's to show the component in the user's preferred language if that exists (we might be on a page available only in a different language), or fall back to the current language, or if that all fails show nothing.
I get Calling unknown method: craft\elements\GlobalSet::locale()
.
I have come to understand that "locales" no longer exist in Craft 3; they're just different "sites" instead. I read in the upgrade guide that in certain cases I can replace .locale(x)
.siteId(x)
or .site(x)
, but siteId
and site
methods do not exist on this object either.
At the moment, where I get this error, componentLocale
is en_ca
. I have two languages and so two sites, which the upgrade process has migrated to:
- handle:
en_ca
, language:en-CA
- handle:
fr_ca
, language:fr-CA
myGlobal
is a craft\elements\GlobalSet
instance.
Is there an equivalent function to the old .locale(x)
to which I can pass en_ca
and get an equivalent (maybe the same) object back?
Failing that, how can I get the same effect?
This answer looked promising, and I tried craft.entries.id(myGlobal.id).site(componentLocale).one()
but that gives nothing, presumably because that's looking for entries where I want a global.
I eventually found that I can do craft.app.getGlobals().getSetByHandle('myGlobalHandle', craft.app.sites.getSiteByHandle(componentLocale).id)
and I think it is doing what I wanted. But yikes. Is there a nicer way?
{{ myGlobal.myGlobalTitle }}
, does themyGlobalTitle
not display in the correct language (i.e. site)?