Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba

Get url of homepage depending on language


Go to End
Reply


7 Posts   3343 Views

Avatar
spierala

Community Member, 80 Posts

9 July 2010 at 9:04pm

Edited: 09/07/2010 9:05pm

Hello,

I know there was a template code to get the correct url of the homepage depending on the current language. But I don´t find it anymore via google. Can somebody help me?

many thx,
florian

Avatar
silverseba

Community Member, 26 Posts

11 May 2011 at 8:55pm

Edited: 11/05/2011 8:56pm

Maybe the answer comes a little late.

Just put the following function in your Page Class:

/**
 * Return the link to the homepage of the current language
 *
 * @return String
 */
public function LinkHomepageCurrLang() {
	return self::get_homepage_link_by_locale(self::get_current_locale());
}

You can then call $LinkHomepageCurrLang in your Template, and it will give you the link to the homepage of the currently selected language.

Avatar
WebSpilka

Community Member, 85 Posts

14 May 2011 at 2:28am

in my sites I use next functions

public function PageByLang($url, $lang) {
      $SQL_url = Convert::raw2sql($url);
      $SQL_lang = Convert::raw2sql($lang);
   
         
      $page = Translatable::get_one_by_lang('SiteTree', $SQL_lang, "URLSegment = '$SQL_url'");
   
      if ($page->Locale != Translatable::get_current_locale()) {
         
         // Fallback to English
         if($page->hasTranslation(Translatable::get_current_locale())){
            $page = $page->getTranslation(Translatable::get_current_locale());
         }else{
            $page = $page->getTranslation('uk_UA');
         }
         
      }
      
      return $page;
   }

and for lang switcher

public function LangMenu() {
		if($this->URLSegment == "Security") return false;
		//$availTransl = Translatable::getTranslations();
		//if(count($availTransl) == 0) {return false;} // якщо не закоментувати не буде виводити флажків для сторінок в ких нема неодного перекладу

		$langs = Translatable::get_existing_content_languages();
		$data = new DataObjectSet();
		
		foreach(array_keys($langs) as $code) {
		
			$page = $this->getTranslation($code);
		
			if (isset($page)) {
				$lang = i18n::get_lang_from_locale($code);
				$data->push(new ArrayData(array(
					'Name' => i18n::get_language_name($lang, true),
					'Title' => $page->Title,
					//'Link' => Director::baseURL() . $page->URLSegment,
					'Link' => $page->Link(),// - правильна адресація яка враховує вкладені лінки
					'Code' => $code
				)));
			}else{
			
				$lang = i18n::get_lang_from_locale($code);
				$data->push(new ArrayData(array(
					'Name' => i18n::get_language_name($lang, true),
					'Title' => i18n::get_language_name($lang, true),
					//'Link' =>  . $page->URLSegment,
					'Link' => Director::baseURL().'?locale='.$code, //if page not set for this locale, then goo to home page 
					'Code' => $code
				)));	

			}
		}
	return $data;
	}

in template

<% control PageByLang(regions,uk_UA) %>

for lang switcher

<% if LangMenu %><% control LangMenu %><a href="$Link" title="$Name.XML"><img src="themes/antisnid/images/lang/{$Code}.png" alt="$Name.XML" /></a><% end_control %><% end_if %>

Avatar
stallain

Community Member, 64 Posts

11 June 2011 at 5:20am

@silverseba Your solution works like a charm, it would deserve to be on the recipes page. Thanks !

Avatar
Pipifix

Community Member, 56 Posts

24 June 2011 at 4:22am

Edited: 24/06/2011 4:23am

I'm trying to use silversebas code. But i get a Fatal error: Call to undefined method Page_Controller::get_homepage_link_by_locale() in /Applications/MAMP/htdocs/dev-boxen/mysite/code/Page.php on line 63? The whole translatable thingy on this project (SS2.4.5) works fine.

For the template i'm using this code

 		<div id="LogoRow" class="row">
		 	<h1 class="eightcol last"><a title="<% _t('stromimzoostyle.HEADERBACKTOHOMEPAGE','Zur&uuml;ck zur Startseite') %>" href="$LinkHomepageCurrLang">$SiteConfig.Title <span><% _t('stromimzoostyle.HEADERBACKTOHOMEPAGE','Zur&uuml;ck zur Startseite') %></span></a></h1>
			
			<% if Translations %>
			<div id="LangSwitcher" class="threecol last"><% _t('stromimzoostyle.HEADERLANGSHOWPAGEIN','Show page in: ') %>
				<% control Translations %>
    				<a href="$Link" hreflang="$Locale.RFC1766" title="Change the language in...">$Locale.Nice</a> | 
				<% end_control %>
				<span class="">$Locale.Nice</span>
			 </div>
		<% end_if %>
		
		</div>

It seems the self::get_current_locale() returns no values. I've tried to return only the current languange.
Any tips on that?

Thanks, Pipifix.

Avatar
silverseba

Community Member, 26 Posts

24 June 2011 at 6:53pm

Edited: 24/06/2011 7:14pm

@Pipifix: My code (for the LinkHomepageCurrLang) must be placed in the Page class, not in the Page_Controller. Maybe that´s why its not working. If that doesn´t solve your problem try calling "Translatable::get_homepage_link_by_locale(Translatable::get_current_locale())".

If you want to have a language switcher, try using this code in your Page_Controller class:

/**
 * Function returns a DataObjectSet with all available languages
 * The current language is always returned as the first DataObject
 *
 * The DataobjectSet contains:
 * - Localised Language Name ($LangName)
 * - Link to homepage of the language ($Link)
 * - 2-digit Language code ($Code)
 * - Language Locale e.g. 'en_GB' ($Locale)
 *
 * Generate a Language selector (which always directs to the homepage of the language) in Template:
 * <% if LanguageSwitcher %>
 *     <ul id="language-switcher">
 *     <% control LanguageSwitcher %>
 *         <li<% if First %> class="current"<% end_if %>><a href="$Link" title="" class="$Code">$LangName</a></li>
 *     <% end_control %>
 *     </ul>
 * <% end_if %>
 *
 * @return DataObjectSet
 */
public function LanguageSwitcher() {
	$langs = Translatable::get_existing_content_languages();
	// stop if only one language is available
	if(count($langs) <= 1) return false;
	$data = new DataObjectSet();
	$currLocale = self::get_current_locale();
	// add current language first
	$data->push(new ArrayData(array(
		'LangName' => i18n::get_language_name(i18n::get_lang_from_locale($currLocale), true),
		'Link' => self::get_homepage_link_by_locale($currLocale),
		'Code' => i18n::get_lang_from_locale($currLocale),
		'Locale' => $currLocale
	)));

	// add all available translations
	foreach(array_keys($langs) as $locale) {
		if($locale == self::get_current_locale()) {
			continue;
		}
		$data->push(new ArrayData(array(
			'LangName' => i18n::get_language_name(i18n::get_lang_from_locale($locale), true),
			'Link' => Translatable::get_homepage_link_by_locale($locale),
			'Code' => i18n::get_lang_from_locale($locale),
			'locale' => $locale
		)));
	}
	return $data;
}

Then use the following code in your Template, to generate a list with links to the homepages of all available translations:

<% if LanguageSwitcher %>
	<ul id="language-switcher">
	<% control LanguageSwitcher %>
		<li<% if First %> class="current"<% end_if %>><a href="$Link" title="" class="$Code">$LangName</a></li>
	<% end_control %>
	</ul>
<% end_if %>

I think this code should be on the "Translatable" doc page anyway...

Avatar
dianaAvila

Community Member, 8 Posts

25 April 2015 at 4:28am

Hi I used @silverseba recipe. Works great in SS 3.1.*

Will anyone be able to elaborate on why should it be placed inside the Page class and not the Page_Controller?

Just looking to understand a little bit better.

Thank you