PHP中的路由条件

PHP中的路由条件,php,controller,twig,Php,Controller,Twig,我如何设置一个条件,如果国家是美国,则setViewFileName将使用哪个在线购物者 public function routeWhich_Online_Shopper_Are_You(Get $request, Twig $response): array { global $CONFIG; if (I18l::getCountryByDomain() !== "GB") { $response->redirect('/');

我如何设置一个条件,如果国家是美国,则setViewFileName将使用哪个在线购物者

public function routeWhich_Online_Shopper_Are_You(Get $request, Twig $response): array
{
    global $CONFIG;

    if (I18l::getCountryByDomain() !== "GB") {
        $response->redirect('/');
    }

    $siteName = $CONFIG['site_name'];
    $siteUrl  = $CONFIG['site_url'];

    $context = [
        'siteName' => $siteName,
        'siteUrl'  => $siteUrl
    ];

    $page = $this->project->config->getPage();
    $response->setViewFilename('Which_Online_Shopper_Are_You/default.html.twig');
    $page->setPageTitle('Which Online Shopper Are You');
    $page->updateMeta();

    return $context;
}

您可以将视图设置为一个变量,可以根据当前国家/地区覆盖该变量

我还确保了美国不会被重定向

更多详细信息作为注释添加到以下代码中:

public function routeWhich_Online_Shopper_Are_You(Get $request, Twig $response): array
{
    global $CONFIG;

    // Add all the allowed countries
    $allowed = ['GB', 'US'];

    // Get the current country
    $currentCountry = I18l::getCountryByDomain();

    // Check if the current country is in the allowed array. If not, redirect
    if (in_array($currentCountry, $allowed) === false) {
        $response->redirect('/');
    }

    // Set the default view
    $viewFile = 'Which_Online_Shopper_Are_You/default.html.twig';

    // Now override the view if the country is US
    if ($currentCountry === 'US') {
        $viewFile = 'Which_Online_Shopper_Are_You_US/default.html.twig';
    }

    $siteName = $CONFIG['site_name'];
    $siteUrl  = $CONFIG['site_url'];

    $context = [
        'siteName' => $siteName,
        'siteUrl'  => $siteUrl
    ];

    $page = $this->project->config->getPage();

    // Let's use our dynamic viewFile variable to set the view
    $response->setViewFilename($viewFile);
    
    $page->setPageTitle('Which Online Shopper Are You');
    $page->updateMeta();

    return $context;
}

谢谢你的回答,先生,如果用户没有使用.co.uk网站,那么发布的代码会将他们重定向到主页。我要做的是为.com站点添加一个页面,但仍然保留GB页面。我应该将变量放在全局$CONFIG;下面吗;?对不起,这对我来说都是新鲜事。再次感谢您的回答。@NoobieSaibot-现在我使用您的代码作为基础,这样您就可以看到它将在何处以及如何实现。基本上,我已经添加了,所以它不会重定向到US或GB,但如果它是US,则会设置不同的视图。@NoobieSaibot-这有意义吗?@NoobieSaibot-请接受答案,以便所有人都知道它已解决。