I need a helper function to get the current language code. I want to use it in a templete file, like /products/view.phtml, only for testing purposes.
Does it already exist?
I have something in mind like the URL-helper
$url = $this->helper('core/url')->getCurrentUrl();
You can get the current locale code this way :
$locale = Mage::app()->getLocale()->getLocaleCode();
Result for answers given in this topic for "Belgium:French" (Be_Fr):
strtolower(Mage::getStoreConfig('general/country/default')); = be
substr(Mage::getStoreConfig('general/locale/code'),0,2); = fr
Mage::app()->getLocale()->getLocaleCode(); = fr_BE
Note that
Mage::app()->getLocale()->getLocaleCode() == Mage::getStoreConfig('general/locale/code')
but with the second one, you can specify an other store than default one (Mage::getStoreConfig('general/locale/code', $storeId)), so I would recommand it.
Afaik there is no such helper function, but you could of course build your own using:
Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getId());
Try
$_language_code = substr(Mage::getStoreConfig('general/locale/code', $_store->getId()),0,2);
where $_store is current store object
You can also use :
$languageCode = Mage::app()->getStore()->getLanguageCode();
Don't forget to configure your store locales in your admin. Go to menu :
System -> Configuration -> General -> Locale Options
And set the correct Locale for each Websites or stores
For use in the html elements lang attribute etc.
echo strtolower(Mage::getStoreConfig('general/country/default')); // "en"
Related
I have spent hours searching to find where magento stores full county name.
We can get a full list of countries using this code:
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
This will return an array with country code and name, I investigated the directory module, and found out this call gets data from the table
directory_county
But this table don't have full county name! So where is it stored?
and how is it retrieved using that call?
Thanks in advance.
Ok so to compensate for my wrong answer. Here is how this works:
/lib/Zend/Locale/Data/en.xml - if your store is in english, else another xml in the same directoery is read. Every country is there and its code under the xml tag <territory>
The xml is cached using the Zend_Cache_Core class.
/lib/Zend/Locale.php - function getTranslation invokes the lib/Zend/Cache/Core.php class
to load from the cache.
Example: If you change the name of some country in en.xml and clear the magento cache. You will see the change when u invoke your code again.
Full country names are not stored in database. Magento uses inbuilt Zend functionality.
Check file: lib/Zend/Locale/Data/Translation.php for full list.
Use the Zend_Local translation.
<?php
$code = 'EN';
echo Mage::app()->getLocale()->getTranslation($code, 'Territory', null, 2);
?>
Use the column 'iso2_code' from the table 'directory_country' for your $code.
Magneto only stores country codes in DB, and relies for names on Zend's Locale module to provide translated names, for different locale.
By the toOptionArray method it invokes the Zend_Locale class to get the translated value.
Refer $name = Mage::app()->getLocale()->getCountryTranslation($data['value']);, which gets to Mage_Core_Model_Locale and then to Zend_Locale.
It decides which of the node from the data to read, by the switch case statement in Zend_Locale_Data::getContent() line# 962, 963
Magento caches the names, so if you make any change to XML files, make sure to clean your cache folder to get what you seek.
I'd like to know which is the cleanest way to insert an url in an email sent by Moodle module.
So far I'm using this formula, what IMHO I don't think is the cleanest way:
$url = $CFG->wwwroot.'/mod/<mymodulename>/view.php?id='.$cm->id;
The things I don't like here are:
Using $CFG->wwwroot
/mod/<mymodulename> needs to be provided always. (Assume here that I'm using a constant instead of a hardcoded string).
I expected Moodle to have a function to provide this out of the box just when providing module script. I've tried moodle_url but this function doesn't provide the path to the php script when used this way:
new moodle_url('view.php?id='.$cm->id);
I just get:
view.php?id=XX
Thanks in advance.
I would do it like this
$url = new moodle_url('/mod/<mymodulename>/view.php', array('id' => $cm->id));
echo html_writer::link($url, get_string('linktitle', 'mod_mymodulename'));
You can use following statement:
This is Absolute path of file
$url = new moodle_url($CFG->wwwroot.'/mod//view.php', array('id' => $cm->id));
I have managed to make my URL i18n compliant using Zend_Controller_Router.
Ie:
en/user/login becomes fr/utilisateur/connexion and both URLs go to the same controller/action.
The problem I am facing is the following
I have a language switcher that is displayed as follow :
Français
English
Italiano
etc.
The currently active language doesn't have an anchor tag, but all others do.
For the languages that have an anchor on them I am building the URL and I want them to be translated in their specific languages.
Currently if I am in French all the urls get builded in french, even if I set the #local key as a param in the URL view helper (tried "#locale" => 'en', "#locale" => new Zend_Locale('en'))
en/utilisateur/connexion
it/utilisateur/connexion
instead of
en/user/login
it/utente/collegamento
because the locale used while building the URL is the one that is defined application wide.
EDIT
I digged a bit deeper in my issue an I found that only the current locale add its resources loaded, which mean I can't get route in the proper language for the route to be built in the right language
My new issue is : how do I load multiple language translation resources?
(I am planning to implement cache in the far future (near release), so I might get better performances)
Hope this helps re the new issue.
"My new issue is : how do I load multiple language translation resources?"
Just a quick caveat to say I didn't write the code below, it was taken from a example app put together by the guys at Zend however it might help to have it broken down like this.
Their approach for the example app was using a csv file containing translations and using your config file (the default one in a new project being application.ini) to specify the path to all your language translation resources.
like this:
;; Languages
language.file.en = APPLICATION_PATH "/../language/en/translate.csv"
language.file.fr = APPLICATION_PATH "/../language/fr/translate.csv"
language.file.de = APPLICATION_PATH "/../language/de/translate.csv"
language.file.es = APPLICATION_PATH "/../language/es/translate.csv"
language.name.zz = Language
language.name.en = English
language.name.fr = Français
language.name.de = Deutsche
language.name.es = Español
And in each csv file, if you are using something like Excel or Open Office to create it, column A would be the original language and column B the translation.
As an example where English is the original language and a Spanish translation is required:
A B
login entrar
logout salir
You could do that for all the words/phrases you want to translate.
If a translation isn't found then the default original word is used.
Your main application bootstrap could have something like this:
protected function _initLanguage()
{
$options = $this->getOptions();
Zend_Registry::set('language',$options['language']);
$langSess = new Zend_Session_Namespace('language');
if (!isset($langSess->translate)) {
$translate = new Zend_Translate('csv', $options['language']['file']['en']);
$langSess->translate = $translate;
}
if (!isset($langSess->locale)) {
$langSess->locale = 'en';
}
Zend_Locale::setDefault($langSess->locale);
}
As the translate object is held in the session you can use it in any of your views etc using something like:
$langSess = new Zend_Session_Namespace('language');
$translate = $langSess->translate;
and:
<?php echo $translate->_('login') ?>
where you want something to be translated on selecting an alternative language. In the example above the word login would appear when English is selected and entrar when Spanish is selected.
There's loads more to Zend_Translate than this and several ways to implement it so I'm not saying this is the best way by any means.
If it helps or if I can give you more info let me know.
Cheers,
Dave
What I am looking for is something where I can easily change the text on a page. I want to set it to a default value and if something is present for a specific page to change it
So it would say something like:
I like stackoverflow
But if the value of website was "reddit" it would instead say
I like reddit
So stackoverlflow would be the default, reddit would be something that is set to overwrite it.
edit:added comment
Scenario I: Domain Name based data handling
If you want to work on the basis of domain, then in Zend Framework you can work with customize routers.
Scenario II: GET/POST based input handling
Otherwise if you want to display on the basis of GET or POST input you can place something default value as
$myDynamicVar = $this->getRequest()->getParam('some_key', 'default-value');
Scenario III: subdomain based input handling
Again you will need to have your custom router for the purpose, in addition to having support of wildcard subdomain names with your hosting provider
In a definitions file:
<?php
/* site.php
* customize this file
*/
class Site
{
static public $name = "stackoverflow";
}
?>
In your page file:
<?php
/* page.php */
include_once 'site.php';
echo "I like {Site::$name}";
?>
I'm posting this question on it's own as I found post one which lacks full explanation or the best way to do it.
Should I use a language file to name items like:
$first_name= 'name';
$last_name = 'last_name';
and then include this file depending on selection?
I have an app which I need to have in two languages.
Will like something in this lines:
http://www.myapp.com/?lang=en
http://www.myapp.com/?lang=es
Should I use a constants file for this purpose?
constants.php
define('OPERATION_NOT_ALLOWED_EN', 'This operation is not allowed!');
define('OPERATION_NOT_ALLOWED_ES', 'This operation is not allowed!');
What is the recommended way of accomplishing this?
You can follow in the footsteps of phpBB - they use a $lang[] array with code that looks like:
$lang['Next'] = 'Next';
$lang['Previous'] = 'Previous';
$lang['Goto_page'] = 'Goto page';
$lang['Joined'] = 'Joined';
$lang['IP_Address'] = 'IP Address';
$lang['Select_forum'] = 'Select a forum';
$lang['View_latest_post'] = 'View latest post';
$lang['View_newest_post'] = 'View newest post';
$lang['Page_of'] = 'Page <b>%d</b> of <b>%d</b>'; // Replaces with: Page 1 of 2 for example
$lang['ICQ'] = 'ICQ Number';
$lang['AIM'] = 'AIM Address';
$lang['MSNM'] = 'MSN Messenger';
$lang['YIM'] = 'Yahoo Messenger';
It is of course included from a file specified in the user's settings, but you'd be fine with your suggestion of ?lang=en in the query string accessing something similar to a constants.php file.
You might want to name the file lang_en.php or something similar for clarity.
That will work for strings like you gave in your example. But there are other complications. For example, do you want to format dates in the appropriate format for the locale (es vs en?). How about formatting of numbers and currencies? Also, you might have "dynamic" messages: "You have $x messages in your inbox". Where you want to pass variables. Check out some of the php localization libraries. Here is an online tutorial: http://www.devx.com/webdev/Article/38732.
Also look at the framework you are using. Many of them have localization support.
How should you implement it? Like Zend_Translate.
I would use locale-specific files with constants, eg:
locale_en.php:
define('GREETING', "Welcome to Widgets Inc');
and
locale_de.php:
define('GREETING', 'Wir begruessen Sie zu Widgets Inc');
in your setup you detect the locale and do:
if ($locale == 'en') {
require 'locale_en.php';
} else if ($locale == 'de') {
require 'locale_de.php';
}
This gives you the benefit of constants and makes localization reasonably transparent to your application in that you don't have to do if ($locale ... all over the place. If anything is locale-specific, just put it in the locale files.
If you want to add a locale file just copy an existing one and change all the references rather than trawling your codebase for them.
You can also put code in these files like correctly formatting numbers and dates for these locales (including the right names in each language but also the use of commas, quotes, periods and so on), currency conversions and displays, etc.
There are free 3rd party controls to do this using an ISO standard XML file (I wrote a database utility to create, edit & export into this format).
The other answers are very manual and involve more work than using this control does.
The control you need is found at:
http://ezcomponents.org/docs/api/trunk/introduction_Translation.html
After the eZ Components are installed on the server, you need to retrieve the base control required for all eZ Components
require_once "ezc/Base/base.php";
/**
* __autoload()
*
* #param mixed $className
* #return
*/
function __autoload( $className )
{
ezcBase::autoload( $className );
}
Then you must define where the XML language file is located (see: ISO639-2, ISO3166, and Qt Linguist)
$config["language_code"] = "en_us"; // as defined by ISO639-2 and ISO3166
// grab our translation XML file
$backend = new ezcTranslationTsBackend( dirname( __FILE__ ). '/translations' );
$backend -> setOptions( array( 'format' => $config["language_code"].'.xml' ) );
// create a manager object
$manager = new ezcTranslationManager( $backend );
$language = $manager->getContext( $config["language_code"], 'strings' );
now you can grab strings by simply calling the following function
getTranslation( "SOME_KEY" );
and to retrieve phrases that have parameters use the following syntax, please note the relation between [KEYWORD] and "keyword" is intentional and recommended
getTranslation( "FIND_[KEYWORD]_BY_[TYPE]", array("keyword" => $keyword, "type" => $type ) );
an example of a TS XML file is (should be called en_US.xml)
<!DOCTYPE TS>
<TS>
<context>
<name>strings</name>
<message>
<source>ZONE_TYPE</source>
<translation>Zone Type</translation>
</message>
<message>
<source>ZONE_TOOL</source>
<translation>Zone Tool</translation>
</message>
<message>
<source>HELLO_[NAME]_WELCOME_TO</source>
<translation>Hello, %name, welcome to Webfood Admin</translation>
</message>
<message>
<source>YOUR_ADMINISTRATIVE_SESSION_HAS</source>
<translation>Your administrative session has timed out. Please login again.</translation>
</message>
</context>
</TS>
I would simply have a setting, in your PHP sessions, that stores the language used, perhaps ask the user before or after they log in which language they want, and store it to their user table if you have accounts. There's no reason to keep sending a URL value over and over, that's a bad idea.