symfony link to change language and stay on the page

扶醉桌前 提交于 2019-12-11 04:38:50

问题


I would like to make a link the will be in the layout to change the language. So it should work for many routes.

for example i'm on the page /en/myModule

and the links should point to /de/myModule /fr/myModule

I found a solution here :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, '&')) ?>

Problem is that I need a default route, and I don't want to have it.

Is there any solution for what I need ?


回答1:


routing:
  user_switch_culture:
   url: /culture-change/:language
   param: { module: user, changeCulture }

In your layout template:

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

Link will generate:

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

In your action:

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")));
}

Just off the top off my head. should work...

Not great: Should do some filter on the redirect to make sure it's the correct domain name etc.




回答2:


Why not make a specific action for this?

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);
}



回答3:


I think that I have a solution:

  $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'));

Is it a good one or is there a better solution ?



来源:https://stackoverflow.com/questions/5343217/symfony-link-to-change-language-and-stay-on-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!