I have one portal and several communities (LR 6.1 - sites). The communities allocate several regions with different languages, hence I would like set different default languages for each community.
Is it possible to set default language by site?
I need it for CMS requirements: every site has a own default language for content. For example site in Germany must have germany as default language, and site in Spain have a spanish as default language and so on.
I'm not aware that configuration setting for default language per site (if you mean community/organization...) exists.
For entire portal you have "Default Language" option under
Control panel -> Portal settings -> Display settings
But if you don't have your language there, or you want to remove/add some languages you can configure that in portal-ext.properties. For example
locales=hr_HR,en_US
EDIT (more info about bug mentioned in comment)
If you take a look at com.liferay.portal.service.impl.CompanyLocalServiceImpl
public void updatePreferences(long companyId, UnicodeProperties properties)
throws PortalException, SystemException {
PortletPreferences preferences = PrefsPropsUtil.getPreferences(
companyId);
try {
String newLocales = properties.getProperty(PropsKeys.LOCALES);
if (newLocales != null) {
String oldLocales = preferences.getValue(
PropsKeys.LOCALES, StringPool.BLANK);
if (!Validator.equals(oldLocales, newLocales)) {
validateLocales(newLocales);
LanguageUtil.resetAvailableLocales(companyId);
}
}
...
}
protected void validateLocales(String locales) throws PortalException {
String[] localesArray = StringUtil.split(locales, StringPool.COMMA);
for (String locale : localesArray) {
if (!ArrayUtil.contains(PropsValues.LOCALES, locale)) {
throw new LocaleException();
}
}
}
you will see that "newLocales" are validate against
if (!ArrayUtil.contains(PropsValues.LOCALES, locale)) {
throw new LocaleException();
}
so if you add new locale key, in Display page of Portal settings, which is not in portal-ext.properties or portal.properties you'll get LocaleException.
Pay attention that oldLocales are read from preferences (database) String oldLocales = preferences.getValue(PropsKeys.LOCALES, StringPool.BLANK);
and validated against portal.properties/portal-ext.properties if (!ArrayUtil.contains(PropsValues.LOCALES, locale)) { ...
PropsValues.LOCALES => public static String[] LOCALES = PropsUtil.getArray(PropsKeys.LOCALES);
As stated in comment this behavior will happen if (and only if) you add new locale (in GUI) that is not in portal.properties
locales=ar_SA,eu_ES,bg_BG,ca_AD,ca_ES,zh_CN,zh_TW,hr_HR,cs_CZ,da_DK,nl_NL,nl_BE,en_US,en_GB,et_EE,fi_FI,fr_FR,gl_ES,de_DE,el_GR,iw_IL,hi_IN,hu_HU,in_ID,it_IT,ja_JP,ko_KR,lo_LA,nb_NO,fa_IR,pl_PL,pt_BR,pt_PT,ro_RO,ru_RU,sr_RS,sr_RS_latin,sl_SI,sk_SK,es_ES,sv_SE,tr_TR,uk_UA,vi_VN
or if you modified locales in portal-ext.properties than if not in portal-ext.properties.
For example if you have in portal-ext.properties
locales=en_GB
you will not be able to add any other locale from GUI unles you first add new locale to portal-ext.properties AND then go to Display page of Portal settings and add it there again.
there might be a way based on how you organize your editors: The default language for web content is based on the current language (e.g. the default language) of the user. Typically german users might have their language set to german, in order to read the german content version, no?
Alternatively you'd have to customize Liferay (e.g. the webcontent editor) and manually set the default language based on some property in the current site - this might be stored as custom field aka expando. This way it will truly be based on the site that content is being created in, but this might conflict with the current user's expectation: What do they set their default language for when the editor doesn't honor this?
Still - in your case the expectation might even be what you describe, so it's a valid option.
Is this level of detail enough?
Related
I've written a console app using the Umbraco (7.1.4) contentService API to move some nodes and rename them in a site redesign. It all works fine except when I rename the document the 'Link to Document' doesn't change. The code is adapted from https://github.com/sitereactor/umbraco-console-example.
private static void MoveNode(IContentService contentService, int nodeId, int newParentId, string newname)
{
//Get the Root Content
var nodeContent = contentService.GetByIds(nodeId.AsEnumerableOfOne()).First();
nodeContent.Name = newname;
contentService.Move(nodeContent, newParentId);
var status = contentService.SaveAndPublishWithStatus(nodeContent);
Console.WriteLine(status);
}
Status is True and the page name is changed when I look at it in back office but the 'Link to Document' doesn't change. Now if I use
var status = contentService.PublishWithChildrenWithStatus(nodeContent);
Then it works but takes a lot longer (minutes), but if I change the name in back office then it only takes seconds but the links are updated correctly. Is there another way to rename a document without Publishing all the children?
(I've left out a bit of code in the above - sometimes it moves sometimes it just renames, but in either case I have to publish with the children to get it to work.)
It seems this happens because the XML cache file has not been updated.
Have a look here for a few ways of doing it
http://our.umbraco.org/wiki/reference/api-cheatsheet/publishing-and-republishing
Or the quickest is just delete APP_Data\umbraco.config - the XML cache file, probably not recommended for Prod but gets things working quickly in dev.
I've tryed this solution here Jsoup set Accept-Language to make my JSoup connection only accept pages that come in english. Unfortunately it didn't work and my output was still:
I don't know if this happened because when the user agent says ("Accept-Language", "en") is to rather take english pages version instead of other languages or really for just accept the english ones. Anyway, the question speaks for itself, if there is a way to, how may I set the JSoup connection to only accept english pages?
Is it possible for you to write a language check method
public String languageCheck(String page){
String result = ""
List<String> pagesArray= new ArrayList<String>();
pagesArray.add(page);
if(pagesArray.get(0)!=null){
char []test = pagesArray.get(0).trim().toCharArray();
if(Character.isLetter(test[0]))
{
System.out.println("ok");
result = "okay"
}else{
System.out.println("Nok");
result = "Not Okay"
}
}
return result;
}
use this method to remove non English pages, hope it helps you
I'm using the Laravel Lang class for localization of my web app. I've added two languages to the languages array in application/config/application.php. This changes the default language it uses for localization to whatever the first part of the URI indicates (e.g. bla.com/en/bla and bla.com/co/bla). Now I need to be able to check what the current default language is in my view. However, the Lang class provides no way of checking this as far as I've been able to figure out, as the Lang::$language variable is protected. Is there any way of checking this apart from manually parsing the URI?
The cleanest way to know the current language of your website in Laravel appears to be :
Lang::locale();
https://laravel.com/api/5.8/Illuminate/Translation/Translator.html#method_locale
It's different than this command that will return the default language of your website :
Config::get('app.locale');
An alternative, a bit shorter way could be using something like this:
app()->getLocale()
The advantage of this is that IDEs such as PHPStorm recognize this function and can help you develop much faster.
BenjaminRH's answer is very good, and his suggested approach works perfectly. I've improved the snippet a bit. Now it detects the browser language and checks if that language is supported according to the application's config file.
It's a quick hack, but it works on my app. Note that the application language is also set now. Feel free to use ore improve it.
Route::filter('before', function()
{
// current uri language ($lang_uri)
$lang_uri = URI::segment(1);
// Set default session language if none is set
if(!Session::has('language'))
{
// use lang in uri, if provided
if(in_array($lang_uri, Config::get('application.languages')))
{
$lang = $lang_uri;
}
// detect browser language
elseif(isset(Request::server('http_accept_language')))
{
$headerlang = substr(Request::server('http_accept_language'), 0, 2);
if(in_array($headerlang, Config::get('application.languages')))
{
// browser lang is supported, use it
$lang = $headerlang;
}
// use default application lang
else
{
$lang = Config::get('application.language');
}
}
// no lang in uri nor in browser. use default
else
{
// use default application lang
$lang = Config::get('application.language');
}
// set application language for that user
Session::put('language', $lang);
Config::set('application.language', $lang);
}
// session is available
else
{
// set application to session lang
Config::set('application.language', Session::get('language'));
}
// prefix is missing? add it
if(!in_array($lang_uri, Config::get('application.languages')))
{
return Redirect::to(URI::current());
}
// a valid prefix is there, but not the correct lang? change app lang
elseif(in_array($lang_uri, Config::get('application.languages')) AND $lang_uri != Config::get('application.language'))
{
Session::put('language', $lang_uri);
Config::set('application.language', $lang_uri);
}
});
In the newer Laravel versions, you can get the current language with:
Config::get('app.locale');
This would work fine
lang="{{ app()->getLocale() }}"
I've figured out a solution to the language problem (thanks to nickstr on the IRC and the accepted answer to this question). It involves storing the current language as a session variable, which is updated when the language uri segment is changed.
Route::filter('before', function()
{
// Do stuff before every request to your application...
// Default language ($lang) & current uri language ($lang_uri)
$lang = 'he';
$lang_uri = URI::segment(1);
// Set default session language if none is set
if(!Session::has('language'))
{
Session::put('language', $lang);
}
// Route language path if needed
if($lang_uri !== 'en' && $lang_uri !== 'he')
{
Return Redirect::to($lang.'/'.URI::current());
}
// Set session language to uri
elseif($lang_uri !== Session::get('language'))
{
Session::put('language', $lang_uri);
}
});
This might help.
Config::get('application.language')
You can use
https://github.com/mcamara/laravel-localization
Laravel Localization uses the URL given for the request. In order to achieve this purpose, a group should be added into the routes.php file. It will filter all pages that must be localized.
// app/routes.php
Route::group(array('prefix' => LaravelLocalization::setLanguage()), function()
{
/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
Route::get('/', function()
{
return View::make('hello');
});
Route::get('test',function(){
return View::make('test');
});
});
/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/
Once this group is added to the routes file, an user can access to all languages added into the 'languagesAllowed' ('en' and 'es' for default, look at the config section to change that option). For example, an user can now access to two different languages, using the following addresses:
http://laravel.com/en
http://laravel.com/es
http://laravel.com
I use App::getLocale() which is probably the most supported way as the App::setLocale('EN') method is used in the documentation.
You can use this method everywhere. If it throughs an error somewhere, you can use \App::... to make it work.
I'm using Laravel 5.0.
Your can get current language in laravel blade by:
{{Lang::locale()}}
The Lang class is specifically for outputting the correct language and as you say manages the language internally.
Looking through the API there is no method to help you directly with this and parsing the URI to get the language would seem the appropriate course of action.
You can always just do this to retrieve the language string in the URI:
$language = URI::segment(1);
Examining Laravel Requests
The Problem:
I'm about to implement language localization to an already very large ipad application that was built using sencha touch wrapped in phonegap. I have the english and spanish translations in json files.
What I'm Planning on Doing:
I plan to load the json files into a sencha touch store, creating a global object. Then in each place where I call text that is displayed, i will replace the text with a call to the global object.
My question(s):
Is there an easier way to implement language localization with my
setup?
Will I run into issues with native sencha stuff (like datepickers)?
When loading/reloading language json files, will I have performance
issues (require a webview reload?, sencha object resizing issues,
etc)
edit 1 : Useful Related Info:
For those going down this road, it quickly becomes useful to write a simple phonegap plugin to get the ipad/iphone device's language setting into your javascript. This requires a plugin, which will look something like this:
Javascript :
part 1:
PhoneGap.exec("PixFileDownload.getSystemLanguage");
part 2(callback Function):
setLanguage(returnedLanguage)
{
GlobalVar.CurrentLanguage = returnedLanguage; //GloablVar.CurrentLanguage already defined
}
Objective C:
-(void)getSystemLanguage:(NSMutableArray*)paramArray withDict:(NSMutableDictionary*)options
{
/*Plugin Details
PhoneGap.exec("PixFileDownload.getSystemLanguage");
Returns Language Code
*/
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:#"AppleLanguages"];
NSString *language = [languages objectAtIndex:0];
NSLog(#"####### This is the language code%#",language);
NSString *jsCallBack;
jsCallBack = [NSString stringWithFormat:#"setLanguage('%#');",language];
[self.webView stringByEvaluatingJavaScriptFromString:jsCallBack];
}
edit 2: character encoding
When adding additional language characters to a sencha project (or any webview phonegap project), ensure that you have the proper encoding specified in the index file. This is the tag i needed.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
I've finished this language localization plugin. It's not amazing, but it worked better than I originally speculated. Here are the short answers to each of the questions.
1- Is there an easier way to implement language localization with my
setup?
Not that i'm aware of. The comment by Stuart provided this link Sencha-touch localization. Use a store or a global JSON object? which had some good information on one way that you can use class overrides. I didn't like this approach, because it spread my language translations into different classes. But certainly, if you are doing something simple, or you want something that could be more powerful, perhaps you should investigate that.
2- Will I run into issues with native sencha stuff (like datepickers)?
I ended up specifically leaving "datepickers" in english for now. But everything else was really relatively easy to customize. Almost every graphical UI element can have it's text altered.
3- When loading/reloading language json files, will I have performance
issues (require a webview reload?, sencha object resizing issues,
etc).
The method that i employed (see below) worked exceptionally well in regards to performance. The one issue that you have is right when you switch the languages, you need that specific page to reload. Sencha handled resizing without any flaws, except where I had been foolish and statically set sizes.
Some of what I did was described in edits to the question. Here is a detailed overview of my solution. (warning, it's not the most elegant solution.)
Instead of using a pure JSON file, I ended up just using a javascript function. This isn't the greatest solution because it requires some minimal maintenance, but JSON parsing with phonegap/sencha isn't the best. (I get JSON files from translater's, and quickly paste into the javascript file. Takes around 2 minutes, see further explanation below).
Language.js
function setLanguage(language)
{
if(language == "en")
{
//console.log("inside if Language == en");
GlobalLanguage.CurrentLanguage = language;
GlobalLanguage.ID = {"glossary": [
{
//CONVERTED JSON
about : 'About',
checking_for_updates : 'Checking for updates...(This may take a few minutes.)'
//Any additional translations
}
]};
}
if (language == "es"){
//console.log("inside language == es");
GlobalLanguage.CurrentLanguage = language;
GlobalLanguage.ID = {"glossary": [
{
//CONVERTED JSON
about : 'Acerca de ',
checking_for_updates : 'Verificando actualizaciones... (Capas que demore algunos minutos).'
//Any additional translations
}]};
}
if (language == "pt"){
//console.log("inside language == pt");
GlobalLanguage.CurrentLanguage = language;
GlobalLanguage.ID = {"glossary": [
{
//CONVERTED JSON
about : 'Sobre',
checking_for_updates : 'Verificando se há atualizações... (pode demorar alguns minutos.)'
//Any additional translations
}]};
}
}
As you can see, this file allows for 3 languages (Portugese, English, and Spanish). After setting the language, you could access each localized string anywhere in your object. For example, if you need to access the word "about" simply use:
GlobalLanguage.ID.glossary[0]["about"]
This will access the GlobalLanguage object which will have whatever language loaded into the properties. So throughout your project, you could have these calls. However, I'd recommend taking it one step further
function langSay(languageIdentifier){
// console.log("inside langSay");
if(!GlobalLanguage.ID.glossary[0][languageIdentifier]){
return "[! LANGUAGE EXCEPTION !]";
}
else{
return GlobalLanguage.ID.glossary[0][languageIdentifier];
}
}
This protects you from having language exceptions and having your program crash without knowing where (you may have hundreds or thousands of properties being set in that language.js file). So now simply :
langSay("about")
One additional note about formatting from JSON. The format you want your language files in is:
languageIdentifier : 'Translation',
languageIdentifier : 'Translation',
languageIdentifier : 'Translation'
I used Excel for the formatting. Also the languageIdentifiers are unique identifiers without spaces. I recommend just using Excel to format first 3 to 4 words word1_word2_word3_word4 of the english translation.
word1_word2_word3 : 'word1 word2 word3'
Hope this helps you out! I'd be happy to respond to any questions
I'm building a site which needs to support both English and Persian language. The site is built with ASP.NET MVC 3 and .NET 4 (C#). All my controllers inherit from a BaseController, which sets culture to "fa-IR" (during test):
Thread.CurrentThread.CurrentCulture = new CultureInfo("fa-IR");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("fa-IR");
In my views, I'm using static helper classes to convert into right timezone and to format date. Like:
DateFormatter.ToLocalDateAndTime(model.CreatedOnUtc)
I'm doing the same for money with a MoneyFormatter. For money, the currency prints correctly in Persian (or, at least I think so as I don't know any Persian. It will be verified later on though by our translators). The same goes for dates, where the month is printed correctly. This is what it displays as currently:
For money:
قیمت: ريال 1,000
For dates:
21:01 ديسمبر 3
In these examples, I want the numbers to also print in Persian. How do you accomplish that?
I have also tried adding:
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
in the HEAD tag, as recommended on some forums. Does not change anything though (from what I can see). I have also added "fa-IR" as the first language in my browser languages (both IE and Firefox). Didn't help either.
Anyone got any ideas on how to solve this? I'd rather avoid creating translation tables between English numbers and Persian numbers, if possible.
Best regards,
Eric
After some further research I found an answer from a Microsoft employee stating that they don't translate numbers, though it's fully possible to do it yourself using the array of digits for a specific culture, that is provided by the NativeDigits property (see http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.nativedigits.aspx).
To find out if text that is submitted in a form is Arabic or Latin I'm now doing:
public bool IsContentArabic(string content)
{
string pattern = #"\p{IsArabic}";
return Regex.IsMatch(
content,
pattern,
RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.Multiline);
}
public bool IsContentLatin1(string content)
{
string pattern = #"\p{IsBasicLatin}";
return Regex.IsMatch(
content,
pattern,
RegexOptions.IgnoreCase | RegexOptions.Multiline);
}
And to convert Persian digits into their "Latin" equivalents, I wrote this helper:
public static class NumberHelper
{
private static readonly CultureInfo arabic = new CultureInfo("fa-IR");
private static readonly CultureInfo latin = new CultureInfo("en-US");
public static string ToArabic(string input)
{
var arabicDigits = arabic.NumberFormat.NativeDigits;
for (int i = 0; i < arabicDigits.Length; i++)
{
input = input.Replace(i.ToString(), arabicDigits[i]);
}
return input;
}
public static string ToLatin(string input)
{
var latinDigits = latin.NumberFormat.NativeDigits;
var arabicDigits = arabic.NumberFormat.NativeDigits;
for (int i = 0; i < latinDigits.Length; i++)
{
input = input.Replace(arabicDigits[i], latinDigits[i]);
}
return input;
}
}
I've also hooked in before model binding takes place and there I convert digit-only input from forms into Latin digits, if applicable.
Ako, for what direction goes we managed to solve quite a bit of issues using the 'dir' attribute (dir => direction) on the html tag for our Web page. Like this:
<html dir="rtl">
The 'dir' attribute takes either "rtl" (right-to-left) or "ltr" (left-to-right).
Hope this helps someone!
Maybe you have to change the font.
If you know your client supports a particular font, say Badr or Nazanin, then you can change the font-family for those numbers, and I think that will work for you.
You can supply for the font for your page, but I think this only works in modern browsers and fails in the old ones. You can check this.
Hope that helps.
How are you printing the numbers to the output? I don't have much experience with localization but you might have to use the appropriate NumberFormatInfo or something similar to format the number.
Also for greatest portability you should probably be using UTF8 as the encoding.
firs of all you should use a font-face that supports Persian number.
I use this technique and I can show Persian number on my web site.
fonts like:BNazanin.