问题
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