I am using a custom Twig extension to add global variables:

class MyGlobals extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
    public function getGlobals()
      // This is a site other than the 'currentSite' according to Craft
      // SiteB does not have its own baseURL
      $siteB = Craft::$app->sites->getSiteByHandle('site-b');
      // The `locationContent` section has propagation settings: 
      // "only save entries to the site they were created in"
      $entry = Entry::find()->section('locationContent')->site($siteB)->one();
      // The correct entry is found, however, no custom field data is populated
      Craft::dd($entry->myCustomTextField); //-> null

      // ...

However, if I execute the same query in a Twig template:

{% set siteB = craft.app.sites.getSiteByHandle('site-b') %}
{{ craft.entries.section('locationContent').site(siteB).one().myCustomTextField }}
{# -> 'The correct value of my custom text field'  #}

I figure this has something to do with the fact that the query in the Twig template is running after Craft has been fully initialized, whereas the query in getGlobals() is executed before. But, I can't see why that would matter.

I have tried manually setting the current site to siteB, same result. I have tried using a custom Twig function to set Twig globals after Craft has been fully initialized:

$twig = Craft::$app->view->getTwig(null, ['safe_mode' => false]);
$siteB = Craft::$app->sites->getSiteByHandle('site-b');
$entry = Entry::find()->section('locationContent')->site($siteB)->one()
$twig->addGlobal('test', $entry->myCustomTextField);
//-> Unable to add global "test" as the runtime or the extensions have already been initialized.

Please help.


I've worked around this by extending the Craft global variable instead of using Twig globals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.