programing tip

codeigniter 웹 사이트를 다국어로 만드는 가장 좋은 방법입니다.

itbloger 2020. 10. 8. 07:47
반응형

codeigniter 웹 사이트를 다국어로 만드는 가장 좋은 방법입니다. lang 배열에서 호출은 lang 세션에 달려 있습니까?


시간과 시간을 조사하고 있지만 명확하고 효율적인 방법을 찾지 못했습니다.

영어로 된 codeigniter 기반 웹 사이트가 있는데 지금 폴란드어를 추가해야합니다. 방문자 선택에 따라 2 개 언어로 사이트를 만드는 가장 좋은 방법은 무엇입니까?

각 언어에 대한 배열 파일을 만들고 lang 선택에서 세션에 따라 뷰 파일에서 호출하는 방법이 있습니까? 데이터베이스를 사용하고 싶지 않습니다.

도움을 주셔서 감사합니다! 마감일이 다 됐습니다 : / 감사합니다 !!


CodeIgniter의 언어 라이브러리를 보셨습니까 ?

언어 클래스는 국제화를 위해 언어 파일과 텍스트 줄을 검색하는 함수를 제공합니다.

CodeIgniter 시스템 폴더에는 언어 파일 세트가 포함 된 언어라는 폴더가 있습니다. 오류 및 기타 메시지를 다른 언어로 표시하기 위해 필요에 따라 고유 한 언어 파일을 작성할 수 있습니다.

언어 파일은 일반적으로 시스템 / 언어 디렉토리에 저장됩니다. 또는 응용 프로그램 폴더 안에 language라는 폴더를 만들어 저장할 수 있습니다. CodeIgniter는 응용 프로그램 / 언어 디렉토리에서 먼저 찾습니다. 디렉토리가 없거나 지정된 언어가없는 경우 CI는 대신 글로벌 시스템 / 언어 폴더를 찾습니다.

귀하의 경우에는 ...

  • 당신은 polish_lang.phpenglish_lang.php내부 를 만들어야합니다application/language/polish
  • 그런 다음 해당 파일 내에 키를 만듭니다 (예 : $lang['hello'] = "Witaj";
  • 그런 다음 컨트롤러에로드하십시오. $this->lang->load('polish_lang', 'polish');
  • 그런 다음 $this->lang->line('hello');이 함수의 반환 값을 변수에 저장하여 뷰에서 사용할 수 있도록 다음 과 같은 줄을 가져옵니다 .

영어 및 필요한 다른 모든 언어에 대해 단계를 반복하십시오.


또한 세션에 언어를 추가하기 위해 각 언어에 대한 몇 가지 상수를 정의한 다음 config / autoload.php에 세션 라이브러리가 자동로드되었는지 확인하거나 필요할 때마다로드합니다. 사용자가 원하는 언어를 세션에 추가합니다.

$this->session->set_userdata('language', ENGLISH);

그런 다음 언제든지 다음과 같이 잡을 수 있습니다.

$language = $this->session->userdata('language');

컨트롤러에서 cunstructor를 만들 때 다음 줄을 추가하십시오.

즉, 이후

parent :: Controller ();

아래 줄 추가

    $this->load->helper('lang_translate');
    $this->lang->load('nl_site', 'nl'); // ('filename', 'directory')

다음 함수로 도우미 파일 lang_translate_helper.php를 만들고 system \ application \ helpers 디렉토리에 넣으십시오.

function label($label, $obj)
{
    $return = $obj->lang->line($label);
    if($return)
        echo $return;
    else
        echo $label;
}

각 언어에 대해 system \ application \ languages ​​아래에 en, nl, fr 등과 같은 언어 약어로 디렉토리를 만듭니다.

아래에 주어진대로 label => language_value 쌍을 보유하는 $ lang 배열을 포함 할 위 (각각) 디렉토리에 언어 파일을 만듭니다.

nl_site_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

en_site_lang.php

$lang['welcome'] = 'Welcome';
$lang['hello word'] = 'Hello Word';

예를 들어, 백엔드 (관리자 섹션) 관리를위한 별도의 언어 파일을 원할 경우 컨트롤러에서 $ this-> lang-> load ( 'nl_admin', '로 사용할 수 있습니다. nl ');

nl_admin_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

마지막으로 원하는 언어로 라벨을 인쇄하려면 아래와 같이 라벨에 액세스하십시오.

label ( 'welcome', $ this);

또는

label ( 'hello word', $ this);

hello & word의 공백을 기록해두면 다음과 같이 사용할 수 있습니다. :)

언어 파일에 정의 된 레이블이없는 경우 함수 레이블에 전달한 내용을 간단히 인쇄합니다.


나는 Randell의 대답 두 번째입니다.

그러나 http://www.maxmind.com/app/php 또는 http://www.ipinfodb.com/ 과 같은 GeoIP는 항상 통합 할 수 있습니다. 그런 다음 codeigniter 세션 클래스로 결과를 저장할 수 있습니다.

ipinfodb.com api를 사용하려는 경우 ip2locationlite.class.php 파일을 codeigniter 애플리케이션 라이브러리 폴더에 추가 한 다음 모델 함수를 생성하여 다음과 같이 애플리케이션에 필요한 모든 geoip 로직을 수행 할 수 있습니다.

function geolocate()
{
    $ipinfodb = new ipinfodb;
    $ipinfodb->setKey('API KEY');

    //Get errors and locations
    $locations = $ipinfodb->getGeoLocation($this->input->ip_address());
    $errors = $ipinfodb->getError();

   //Set geolocation cookie
   if(empty($errors))
   {
       foreach ($locations as $field => $val):
            if($field === 'CountryCode')
            {
                $place = $val;
            }
       endforeach;
   }
   return $place;
}

더 쉽게 사용할 수 있도록 CI가 이것을 업데이트했기 때문에

$this->load->helper('language');

및 텍스트 번역

lang('language line');

라벨 내부를 휘게하려면 선택적 매개 변수를 사용하세요.

lang('language line', 'element id');

이것은 출력됩니다

// becomes <label for="form_item_id">language_key</label>

For good reading http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html


I've used Wiredesignz's MY_Language class with great success.

I've just published it on github, as I can't seem to find a trace of it anywhere.

https://github.com/meigwilym/CI_Language

My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.


When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.

You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.

String is totally free so please check it out and tell us what you think.

It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string


Follow this https://github.com/EllisLab/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n

its simple and clear, also check out the document @ http://ellislab.com/codeigniter/user-guide/libraries/language.html

its way simpler than


I am using such code in config.php:

$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...

if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
    case 'ru':
        $config['language'] = 'russian';
        setlocale(LC_ALL,'ru_RU.UTF-8'); 
        break;
        case 'uk':
        $config['language'] = 'ukrainian';
        setlocale(LC_ALL,'uk_UA.UTF-8'); 
                break;
        case 'foo':
        $config['language'] = 'foo';
        setlocale(LC_ALL,'foo_FOO.UTF-8'); 
                break;
        default:
        $config['language'] = 'english';
        setlocale(LC_ALL,'en_US.UTF-8'); 
        break;
}

.... and then i'm using usualy internal mechanizm of CI

o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.

So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application


you can make a function like this

function translateTo($language, $word) {  
   define('defaultLang','english');  
   if (isset($lang[$language][$word]) == FALSE)  
      return $lang[$language][$word];  
   else  
      return $lang[defaultLang][$word];  
}

Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:

1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)

2. Go to the file named setting.php in application/modules/settings/views/setting.php. Here you find the array

<?php /*

 $lang = array (
  'english' => 'English',

  'arabic' => 'Arabic',  // i add this here

  'spanish' => 'Español'

Now save and run the application. It's worked fine.

참고URL : https://stackoverflow.com/questions/1328420/the-best-way-to-make-codeigniter-website-multi-language-calling-from-lang-array

반응형