Showing posts with label localization. Show all posts
Showing posts with label localization. Show all posts

Saturday, August 11, 2018

Django's get_current_language always returns “en”

Leave a Comment

In my Django 2.0 site, I want to set the lang atribute of the html tag to the current locale's language. In my base.html which other templates extend, I use get_current_language in the following way

{% load i18n %}  {% get_current_language as LANGUAGE_CODE %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}">  ... </html> 

The site has translations for multiple languages. If I switch the language in the browser, I see the correct translations, but the lang attribute will always contain en.

In my settings.py I have

USE_I18N = True LANGUAGE_CODE = 'en-us' 

and based on the suggestion of Goran the following middleware order

MIDDLEWARE = [     'django.contrib.sessions.middleware.SessionMiddleware',     'django.middleware.locale.LocaleMiddleware',     'django.middleware.common.CommonMiddleware',     'django.middleware.csrf.CsrfViewMiddleware',     'django.contrib.auth.middleware.AuthenticationMiddleware',     'django.contrib.messages.middleware.MessageMiddleware', ] 

The LANGUAGES setting is unset.

As suggested by Kostadin Slavov I have tried printing the language from the view. It seems that get_current_language calls django.utils.translation.get_language, so I have inserted the following in my view

from django.utils import translation                                         print(translation.get_language())                                            

It prints the correct value (eg de when accessing the view with a browser set to German).

What else am I missing?

1 Answers

Answers 1

I tried to simulate your environment with these steps:

$ cd ~ $ python3 -m venv ~/venvs/mysite $ source ~/venvs/mysite/bin/activate $ pip install django==2.0.8 $ django-admin startproject mysite 

Then I updated the generate code as in your example:

  • mysite/settings.py

    ... MIDDLEWARE = [     'django.middleware.security.SecurityMiddleware',     'django.contrib.sessions.middleware.SessionMiddleware',     'django.middleware.locale.LocaleMiddleware',     'django.middleware.common.CommonMiddleware',     'django.middleware.csrf.CsrfViewMiddleware',     'django.contrib.auth.middleware.AuthenticationMiddleware',     'django.contrib.messages.middleware.MessageMiddleware',     'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... TEMPLATES = [     {         'BACKEND': 'django.template.backends.django.DjangoTemplates',         'DIRS': ['templates'],         'APP_DIRS': True,         'OPTIONS': {             'context_processors': [                 'django.template.context_processors.debug',                 'django.template.context_processors.request',                 'django.contrib.auth.context_processors.auth',                 'django.contrib.messages.context_processors.messages',             ],         },     }, ] ... 
  • mysite/urls.py

    from django.contrib import admin from django.urls import path from django.views.generic.base import TemplateView  urlpatterns = [     path('', TemplateView.as_view(template_name='base.html'), name='home'),     path('admin/', admin.site.urls), ] 
  • templates/base.html

    {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}"> <body> <pre>LANGUAGE_CODE = {{ LANGUAGE_CODE }}</pre> <body> </html> 

With the Django generated code and my few above updates I can see different language code if I switch the language of my browser visiting http://localhost:8000/ after starting it with:

$ python manage.py runserver 

Try my steps on your local environment and check if it works, and then compare your project to the code above.

Update

Try to use diffsettings to see "differences between the current settings file and Django’s default settings".

Read More

Thursday, April 12, 2018

Hamburger menu icon ☰ not appearing on Japanese safari

Leave a Comment

I have some basic HTML that contains a hamburger menu character, something like this:

<div>☰</div> 

The problem is that the character is not visible on Japanese browsers. I have <meta charset="utf-8"> in the head.

What would I need to do to make it work?

Thanks.

7 Answers

Answers 1

Maybe you can get better results using svg.

You must check if the font you are using contains that character.

<svg encoding="UTF-8" >    <text x="10"  y="50" font-size="55">      &#8801;    </text>  </svg>

You can also set the font family from here. (Import?)

See https://developer.mozilla.org/fr/docs/Web/SVG/Element/text

There is alternative icons that can maybe works directly. (Source from personal script)

☰TRIGRAM FOR HEAVEN Hex: 2630 | Dec: 9776 ☱TRIGRAM FOR LAKE Hex: 2631 | Dec: 9777 ☲TRIGRAM FOR FIRE Hex: 2632 | Dec: 9778 ☳TRIGRAM FOR THUNDER Hex: 2633 | Dec: 9779 ☴TRIGRAM FOR WIND Hex: 2634 | Dec: 9780 ☵TRIGRAM FOR WATER Hex: 2635 | Dec: 9781 ☶TRIGRAM FOR MOUNTAIN Hex: 2636 | Dec: 9782 ☷TRIGRAM FOR EARTH Hex: 1D0D3 | Dec: 118995 

Check also the following snippet: It will generate all unicodes chars that your browser can currently display. It may ease your search!

var i = 0      do document.write("<a title='(Linux|Hex): [CTRL+SHIFT]+u"+(i).toString(16)+"\nHtml entity: &# "+i+";\n&#x"+(i).toString(16)+";\n(Win|Dec): [ALT]+"+i+"' onmouseover='this.focus()' onclick='this.href=\"//google.com/?q=\"+this.innerHTML' style='cursor:pointer' target='new'>"+"&#"+i+";</a>"),i++      while (i<136690)  window.stop() 
From What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Answers 2

Without access to a Japanese browser I'm assuming (as others have) that the issue is at the font level. i.e. there is no glyph for the code point U+2630.

Assuming that your page is also served correctly with the encoding as Content-Type: text/html; charset=UTF-8 the issue of HTML encoding should be redundant.

Personally I would use an icon font like Font Awesome to guarantee rendering in all browsers/platforms. Japanese browsers aside, you just don't know what platforms have missing glyphs in their fonts.

As others have pointed out, font files can be large, so I would use the excellent IcoMoon to create a custom font with only the glyphs I need. I do this on my site with 94 icons from various packages and the font files are about 23k.

Alternatively (and for this example, quickest) you could use a standard Unicode font like Google's Noto Sans. Google fonts also allow you to request only the symbols you need, so you can keep the size small there too.

See my example Codepen pulling just one glyph from Noto Sans.

Answers 3

There may be reason that there is no font in the system where the browser runs contains a glyph for “☰” U+2630 TRIGRAM FOR HEAVEN.

Below are some other options to achieve this:

  1. Create your own Menu icon using pure CSS and HTML like below:

.hamburger-icon {    padding: 19px 16px;    display: inline-block;    position: absolute;    top: 0;    left: 0;  }    .hamburger-icon span {    width: 40px;    background-color: #000;    height: 5px;    display: block;    margin-bottom: 6px;  }    .hamburger-icon span:last-child {    margin-bottom: 0px;  }
<div>    <label class="hamburger-icon">      <span>&nbsp;</span>      <span>&nbsp;</span>      <span>&nbsp;</span>   </label>  </div>

  1. Use an image of Menu icon

  2. Use a downloadable font with @font-face. This will take few megabytes to load.

Answers 4

Try this:

<div>&#8801;</div>

By using the character UNICODE U+2261 (8801), ≡ or called by IDENTICAL TO, seems it will reduce font support issues on devices. Or use

<div>&equiv;</div>

According to my experience, it works most of the time.

Also, this link could help you. http://graphemica.com/%E2%89%A1

Answers 5

Why you don't just take a screen of that symbol?

Like <div> <img src="example.png"> </div> ?

Answers 6

Simply:

<div>&#9776;</div>

Answers 7

You could always use bootstrap for your hamburger menu. Here is a link to the tutorial - https://mdbootstrap.com/components/bootstrap-hamburger-menu/

Read More

Monday, March 12, 2018

Set Locale from App - Back Button Issue

Leave a Comment

I am working on Language setting on my app. I was able to change the locale from my Main Activity through the use of

Resources resources = getResources(); Configuration configuration = resources.getConfiguration(); DisplayMetrics displayMetrics = resources.getDisplayMetrics(); configuration.setLocale(new Locale("ar")); resources.updateConfiguration(configuration,displayMetrics); recreate(); 

Everything worked fine but I noticed that the back button did not change its direction to RTL:

enter image description here

This is my expected behaviour when I set the language to a RTL language:

enter image description here

Is this possible?

3 Answers

Answers 1

Try to call this method when you set arabic language:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void forceRTLIfSupported() {     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){        //HERE CHECK CONDITION FOR YOUR LANGUAGE if it is AR then       //change if it is english then don't        getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);       } } 

Answers 2

Changing the navigation bar's direction means that the app will change the Locale of the device. Such a thing is similar to setting the device language in the language setting of the device since a Locale defines the language and direction (rtl or ltr) of the views to support the language. Since you're only changing the Locale of your Context in the app, it will not affect the Context of the other apps on the device and the system apps/components (launcher, navigation bar, status bar, etc...). Hence the navigation bar will not change and stay unaffected by the change in your app.

Furthermore, to alter the device Locale or any other configuration (font, font size, display metrics, rotation, etc..), the app would need the SET_CONFIGURATION permission to do so. Although it is not stated in the docs, the SET_CONFIGURATION permission can only be given automatically to system apps like the language and display settings. I haven't seen if it can be requested from the user by a third party app but I believe that it cannot be as most of the times in the development of my apps, the permission was being granted using adb shell pm grant command in the command line. Usually I would do that during my tests since my apps also support other languages and would want to make sure that the app performs well in such cases, hence I'd grant it the permission in the command line and let it to change the locale of the device from within the tests.

Answers 3

The direction of the navigation bar (and other parts of the OS, like the Settings), is not related to an app. A user can have a LTR OS with a RTL app. thus changing your app's locale and direction does not affect the underlying OS and the user has to change it manually.

Read More

Friday, February 23, 2018

Force Localize Internal Frameworks like UIKit without App restart

Leave a Comment

I have to add an option of switching language inside the app only. I am just stuck on with localizing internal framworks. Can anyone help me with localization of internal framework like UIKit etc from the app itself without restart. My code works fine but for the case of internal framework requires a restart. Just the internal frameworks are not getting localized.

My current code is :

Create a file named BundleExtension.swift and add the following code to it -

var bundleKey: UInt8 = 0  class AnyLanguageBundle: Bundle {  override func localizedString(forKey key: String,                               value: String?,                               table tableName: String?) -> String {      guard let path = objc_getAssociatedObject(self, &bundleKey) as? String,         let bundle = Bundle(path: path) else {              return super.localizedString(forKey: key, value: value, table: tableName)     }      return bundle.localizedString(forKey: key, value: value, table: tableName)   } }  extension Bundle {  class func setLanguage(_ language: String) {      defer {          object_setClass(Bundle.main, AnyLanguageBundle.self)     }      objc_setAssociatedObject(Bundle.main, &bundleKey,    Bundle.main.path(forResource: language, ofType: "lproj"), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)   } } 

Now whenever you need to change the language call this method :

func languageButtonAction() {     // This is done so that network calls now have the Accept-Language as "hi" (Using Alamofire) Check if you can remove these     UserDefaults.standard.set(["hi"], forKey: "AppleLanguages")     UserDefaults.standard.synchronize()      // Update the language by swaping bundle     Bundle.setLanguage("hi")      // Done to reintantiate the storyboards instantly     let storyboard = UIStoryboard.init(name: "Main", bundle: nil)     UIApplication.shared.keyWindow?.rootViewController = storyboard.instantiateInitialViewController() } 

4 Answers

Answers 1

Check this demo, it will work for you.

Link

Answers 2

your code seems good but what I've tried is...

When change language from app then...

Bundle.setLanguage("fr") UserDefaults.standard.set(["fr"], forKey: kAppleLanguages) UserDefaults.standard.synchronize()  NotificationCenter.default.post(name: NSNotification.Name.init("AppLanguageChangeNotification"), object: nil) 

so whenever language is changed this notification will be fired and the view controller who added observer to this will be notified and according to that language need to be changed.

Add observer

NotificationCenter.default.addObserver(viewController, selector: #selector(self.setLocalization), name: NSNotification.Name.init("AppLanguageChangeNotification"), object: nil) 

Method

@objc fileprivate func setLocalization() {      self.lblProfile.text = NSLocalizedString("lblProfile", comment: "")     self.lbDetails.text = NSLocalizedString("lblDetails", comment: "")     .     . } 

Yes, this is bit log process as you need to have all IBOutles to set the localise text.

Answers 3

It depends on what particular framework you want to localize. This is needed to know where from this framework gets its localizations. For most of the cases it is impossible cause you'll have to hardcode path to localizations file of the framework or know something about framework which breaks one of the framework idea: know less about implementation, all you should know is interface.

To achieve what you want you should have the only source for localizations.

With pods or some other non-system frameworks you can fork them and change it so you could pass your strings to it.

With system libraries it may be impossible cause there is no chance to change it in some way. But all cases I know can be implemented with the help of these system libraries, I'm talking about localized navigation bar buttons, for example. You can make your own button and set its title to whatever you want.

Hope it helps. If not, then you can show the example of what exactly you cannot localize and I'll try to help you.

Answers 4

I faced with the same problem and only solution for me was fully reload all UIViewController

Read More

Friday, March 18, 2016

Windows Cordova App (Universal 10 Phone & 8.1 Phone) Building and Packaging Issue

Leave a Comment

I have an issue with packaging a Cordova Windows app targeting Windows Phone 10 Universal Phone and Windows Phone 8.1.

My app is developed in JS & HTML targeting iOS, Android and Windows with Cordova. When building & packaging on Windows I have the following issues:

  1. I could not create a bundle which would be recognized as supporting multiple languages by the windows store. I had the following resource token in the appxmanifest: <Resource Language="x-generate"> but then it would only detect my default language which I set to de-CH. I then replaced this token with the actual language tokens: <Resource Language="de-CH"><Resource Language="fr-CH">.... When building, VS2015 would complain that there are no resources for the default language and I had the same Issue as before, the app would only be recognized as supporting 1 language. After googling around a bit and taking a look at the Localization Example I added the following to my CordovaApp.Windows.jsproj (WinPhone10) and CordovaApp.Phone.jsproj (WinPhone8.1) File:

    <ItemGroup>   <Content Include="strings\de-CH\resources.json" />   <Content Include="strings\fr-CH\resources.json" />   <Content Include="strings\it-CH\resources.json" />   <Content Include="strings\en-US\resources.json" /> </ItemGroup> 

    and

    <ItemGroup>   <PRIResource Include="strings\de-CH\resources.resjson" />   <Content Include="strings\de-CH\resources.json" />   ...[These two lines repeated for every other language]... </ItemGroup> 

    I of course also created this folder structure (strings\de-CH\..., etc.) in my project. The .json and .resjson files only contain the following content: {} as I do not use the native localization features. This did actually work and the store correctly identified the app as being multilingual. BUT it started building _language-fr.appx, etc. binaries and added them to the bundle. The problem with this is that I only target the arm architecture as one of the plugins I use needs to be built against specific architectures and does not support the neutral target. But strangely the Windows Phone 10 Universal bundle now contains the _language-x.appx files compiled as neutral: Bundle contents on the Windows Store show neutral appx This breaks the display of the Supported processors section on the Windows Store as this now lists neutral, arm or x86, x64, arm depending on which platform you look at it. What can I do to fix this? I need the store to recognize the different languages but without building against neutral.

  2. My second issue is in regard to the Supported operating systems section in the Windows Store. Here I have the issue that it shows:

    Windows Phone 10 Windows Phone 8.1 Windows Phone 8 

    And for a while it also showed Windows Phone 7 which mysteriously disappeared... But I still only target the first two. As you can see from the screenshot above, the store recognized the Windows Phone 8.1 build correctly and I only uploaded the two visible builds. I do not want to target Windows Phone 8. For the Windows Phone 10 appxmanifest I have the following entry:

    <Dependencies>   <TargetDeviceFamily MaxVersionTested="10.0.10586.29" MinVersion="10.0.10586.0" /> </Dependencies> 

    Which was mostly default, I only adjusted the MaxVersionTested and added the Name="Windows.Mobile" (I did not yet build & submit with the Name property set like this), just to be on the safe side. In the Windows Phone 8.1 appxmanifest I've had the following entry:

    <Prerequisites>   <OSMinVersion>6.3.1</OSMinVersion>   <OSMaxVersionTested>6.3.1</OSMaxVersionTested> </Prerequisites> 

    I checked the Version codes for Windows Phone 8.1 and they look very different. These versions look like normal Windows 8.1 version codes. The Windows Phone 8.1 version codes are longer but the properties in the appxmanifest only allow versions with 3 places. Would it help or even work if I changed it to the following:

    <Prerequisites>   <OSMinVersion>8.10.14147</OSMinVersion>   <OSMaxVersionTested>8.10.15148</OSMaxVersionTested> </Prerequisites> 

Just to be clear, the appxmanifests of the project are:

package.phone.appxmanifest for Windows Phone 8.1 package.windows10.appxmanifest for Windows Phone 10 Universal 

It would be great if someone could help me with these two issues. Thanks a lot in advance!

0 Answers

Read More

Wednesday, March 9, 2016

Tool to organize translations in JSON files

1 comment

I'm investigating different translation tools for my Angular app. So far, angular-translate seems to be a good solution for that. It uses per-language JSON files that are structured like "lang/NAMESPACE/LANG.json" (e.g. "lang/user/de.json") and look like this:

{   "key1": "Value1",   "key2": "Value2",   "key3": "Value3",   } 

Optionally, the JSON might also be nested.

This seems to be easy to use. However, is slightly inconvenient when actually adding new or changing existing translations. You have to change back and forth different language files and it is cumbersome to find a translation for a certain key. Comparing different translations is also inconvenient.

Is there any tool that can read local translation files and is able to show different translations side-by-side for each key? Either an application (Mac OS support is a must) or browser-based.

2 Answers

Answers 1

Take a look at angular-translate: https://github.com/angular-translate/angular-translate

for all DIY folks:

You can find localized files for angular: here

These files will help you with the build-in angular filters: date, currency and number. Amazing... so far.

Now you want to use your own texts, than all you need is the power of angular.js dependency injection. Create a new file like: "myTexts_en_us.js" and use $provide.value like this:

$provide.value("myTexts", {firstText : "This is my localized text"}); 

For details: http://jsfiddle.net/4tRBY/24/

For real-world-use, you should add a filter: http://jsfiddle.net/4tRBY/41/

Tips:

  • Make sure to insert your new localization-file into your html by hand, JS or Server. (Server is the best choice here!)
  • if you include one of the angular-local files, you do not need to set it up in your app module. (you will have $locale automatically - see the fiddle)
  • add an id key to your $provide-value - and set the value to a language code you are using in your file - this will be come in handy for testing.

Answers 2

I needed the same thing myself and so I just wrote it like this:

I had 2 dropdowns with existing languages, from language 1 to language 2 was the idea.

on select both language I read the json files into arrays and displayed it with an ng-repeat using two way bindings so when the content of an input field changed, the array got updated instantly.

The apply method then uploaded the filename and the array towards a php file which wrote it to the document.

eng.json:

{   "ALBUM":{     "TITEL":"album",     "LAAD_MEER":"Load more",     "ALBUMS":"Back to albums"   },   "INFO":{     "TITEL":"information",     "HOTELS":"Hotels",     "SPORTHAL":"Sportscenter",     "INTHISHOTEL":"In this facility"   } } 

my html:

<section ng-if="toSelected"          class="bg-g-r bg-u-1 card flyin"          ng-repeat="section in fromContents"          id="{{'trans'+section.TITEL}}"          class="translatorSection">      <p class="paddedText bg-u-1 blueElement">{{section.TITEL}}</p>     <div class="textContainer bg-u-1"          ng-repeat="line in section">         <p style="color:grey">{{line}}</p>         <textarea class="bg-u-1" ng-model="toContents[getKeys(toContents,$parent.$index)][getKeys(section,$index)]"                 style="padding: 8px;border-radius: 10px"                 ></textarea>     </div> </section> 

my controller:

//Bound to the dropdowns in my case $scope.fromSelected = null; //language from wich to start $scope.toSelected = null; //language i wish to extend  $scope.fromContents = null; $scope.toContents = null;  $scope.$watch('fromSelected', function (abbr) {     if(abbr) {         jsonFactory.getLanguageContents(abbr).then(function (data) {             $scope.fromContents = data.data;         });     } }); $scope.$watch('toSelected', function (abbr) {     if(abbr) {         jsonFactory.getLanguageContents(abbr).then(function(data){             $scope.toContents = data.data;         });     } });  $scope.getKeys = function (array,index){     return Object.keys(array)[index]; };  $scope.getToValueByKey = function (key){     return $scope.toContents[key]; };  $scope.apply = function (){                 jsonFactory.UploadLanguage($scope.toSelected,$scope.toContents)         .then(function(data){             alert('update succesfull, please reload')         }); }; 

Jsonfactory:

    function getLanguageContents(lang) {         var deferred = $q.defer(),             httpPromise = $http.get('languages/'+lang+'.json');          httpPromise.then(function (response) {             deferred.resolve(response);         }, function (error) {             console.error(error);         });          return deferred.promise;     }         function UploadLanguage(lang,content){             return $q(function(resolve,reject){                 var xmlhttp,                     params = 'lang='+lang+'&content='+JSON.stringify(content);                  if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari                     xmlhttp = new XMLHttpRequest();                 }                 else { // code for IE6, IE5                     xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');                 }                  xmlhttp.open('POST', 'http://localhost:63342/website/app/php/translator.php', true);                 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');                 xmlhttp.onreadystatechange = function() {                     if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {                         var data = xmlhttp.responseText;                         resolve(data);                     }else if (xmlhttp.readyState === 4){                         reject('not found');                     }                 };                 xmlhttp.send(params);             });         } 

Read you folder with json files in javascript into some arrays, For each array just create an ng-repeat using input fields so you see the key and all you translations with it, when you made changes create a button that sends you array and the language filename to this php script: (i only accept one language at the time)

<?php   header("Access-Control-Allow-Origin: *");   $taal = $_POST["lang"];   $content = $_POST["content"];   $myfile = fopen("../languages/".$taal.".json", "w");   fwrite($myfile, $content);   fclose($myfile);   echo $taal;   echo $content; ?> 

It was actually very easy to create, I wanted to add it to my site, so everyone could help translating but it never got there.

I cant give all the code, but i thik this should get you started.

Read More