【问题标题】:symfony link to change language and stay on the pagesymfony 链接更改语言并停留在页面上
【发布时间】:2011-07-17 15:00:15
【问题描述】:

我想在布局中创建一个链接以更改语言。所以它应该适用于许多路线。

例如 我在 /en/myModule 页面上

并且链接应该指向 /de/myModule /fr/myModule

我在这里找到了解决方案:http://oldforum.symfony-project.org/index.php/m/70452/

<?php echo link_to(
  'Germany', 
  '@default?' . http_build_query(array(
    'sf_culture' => 'de', 
    'module' => $sf_request->getParameter('module'), 
    'action' => $sf_request->getParameter('action'))
  ), null, '&')) ?>

问题是我需要一个默认路由,我不想拥有它。

我需要什么解决方案吗?

【问题讨论】:

  • 为什么不想使用默认路由?

标签: php symfony1 internationalization


【解决方案1】:
routing:
  user_switch_culture:
   url: /culture-change/:language
   param: { module: user, changeCulture }

在您的布局模板中:

<?php echo link_to(image_tag("flags/gb.gif"), "user_switch_culture", array("language"=>"en", "redirect"=>$sf_request->getUri())) ?>

链接会生成:

http://example.com/culture-change/fr?redirect=http//example.com/fr/control-panel

在你的行动中:

public function executeChangeCulture(sfWebRequest $request)
{
    $oldCulture = $this->getUser()->getCulture();
    $newCulture = $request->getParameter("language");
    $this->getUser()->setCulture($newCulture);
    return $this->redirect(str_replace('/'.$oldCulture.'/', '/'.$newCulture.'/', $request->getParameter("redirect")));
}

就在我的头顶。应该可以...

不太好:应该对重定向做一些过滤,以确保它是正确的域名等。

【讨论】:

    【解决方案2】:

    为什么不为此采取具体行动?

    public function executeChangeLanguage(sfWebRequest $request)
    {
      if (in_array($request->getParameter('lang'), sfConfig::get('app_site_languages'))
      {
       $this->getUser()->setCulture($request->getParameter('lang'));
      }
    
      // you can ask the browser for referrer or send a parameter to the change language action
      // something like '/change-language?lang=ro&redirect=your page'.
      // if you are sending a redirect parameter you must make sure that it's actually a page within your site
      $referrer = $request->getReferer();
      // or $referrer = $request->getParameter('redirect');
    
      // you can further check the referrer here
      return $this->redirect($referrer);
    }
    

    【讨论】:

    • 就像最后一条评论中所说的,你必须检查推荐人(见评论// you can further check the referrer here)。否则有些人可能会出于自己的目的使用您的重定向
    【解决方案3】:

    我认为我有一个解决方案:

      $uri = sfContext::getInstance()->getRouting()->getCurrentRouteName();
      echo link_to('French', $uri, array('sf_culture'=>'fr')) . ' | ';
      echo link_to('English', $uri, array('sf_culture'=>'en')) . ' | ';
      echo link_to('German', $uri, array('sf_culture'=>'de'));
    

    这是一个好的还是有更好的解决方案?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多