Rails : 자바 스크립트 문자열의 국제화?
따라서 국제화를 전혀 지원하지 않는 기존 Rails 2.3.5 앱이 있습니다. 이제 저는 Rails I18n에 익숙하지만 .NET 내부에 많은 출력 문자열이 있습니다 /javascripts/
. 저는이 접근 방식의 열렬한 팬은 아니지만 안타깝게도 지금 고치기에는 너무 늦었습니다.
Rails 앱에서 JS 파일에 저장된 문자열을 어떻게 국제화 할 수 있습니까? Rails는 JS 파일도 제공하지 않습니다.
나는 항상 Rails 앱이 JS 파일을 제공하도록 할 수 있다고 생각하지만 그것은 꽤 심한 것 같습니다. 이를위한 플러그인이 있습니까?
다음과 같이 간단한 것이 아닌 이유
<script type="text/javascript">
window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>
</script>
그런 다음 JS에서 다음과 같은 작업을 수행 할 수 있습니다.
I18n["en-US"]["alpha"]["bravo"];
응용 프로그램 도우미에 내 것을 래핑했습니다.
def current_translations
@translations ||= I18n.backend.send(:translations)
@translations[I18n.locale].with_indifferent_access
end
그런 다음 내 application.html.erb의 호출은 다음과 같습니다.
<script type="text/javascript">
window.I18n = <%= current_translations.to_json.html_safe %>
</script>
이를 통해 JavaScript에서 현재 로케일을 알 필요가 없습니다.
I18n["alpha"]["bravo"];
또는
I18n.alpha.bravo;
발리 부는 버려졌습니다. i18n-js 사용 : https://github.com/fnando/i18n-js
위의 Ryan의 솔루션은 완벽하지만 백엔드가 아직 초기화되지 않은 경우 초기화해야합니다.
I18n.backend.send(:init_translations) unless I18n.backend.initialized?
# now you can safely dump the translations to json
Rails 3 애플리케이션의 경우 다음을 수행 할 수 있습니다.
i18n.js.erb 파일을 만들고 application.js에 추가합니다. 그리고이 코드를 파일에 추가합니다.
<%
@translator = I18n.backend
@translator.load_translations
@translations ||= @translator.send(:translations)[I18n.locale][:javascript]
%>
window.I18n = <%= @translations.to_json.html_safe %>
또한 큰 자바 스크립트 파일이 없도록 번역 범위를 지정합니다. 내 범위는 : javascript입니다.
누군가에게 도움이되기를 바랍니다!
Javascript 파일에서 단순히 다음을 수행하지 마십시오.
var a_message = "<%= I18n.t 'my_key' %>"
이 작업을 수행하려면 Javascript 파일 확장자에 .erb를 추가해야합니다.
ruby> = 2.0을 사용하지 않는 경우 자바 스크립트 파일 상단에 다음 줄을 추가해야 할 수도 있습니다.
<%# encoding: utf-8 %>
자세한 내용은이 스레드에서 승인 된 답변의 마지막 댓글을 참조하십시오. 레일스 자산 파이프 라인을 사용하는 자바 스크립트 파일의 인코딩 문제
Babilu 는이 작업을 수행하는 Rails 플러그인입니다.
도움이 될 수있는 또 다른 옵션 :
사용 가능한 모든 언어를 포함하는 모델 언어 (슬러그)가 있다고 가정합니다. 누락 된 번역이있는 경우를 처리합니다 (기본 로케일 버전으로 대체 됨).
assets / javascript / i18n.js.erb
<%
@translator = I18n.backend
@translator.load_translations
translations = {}
Language.all.each do |l|
translations[l.slug] = @translator.send(:translations)[l.slug.to_sym]
end
@translations = translations
%>
window.I18n = <%= @translations.to_json.html_safe %>
window.I18n.t = function(key){
if(window.I18n[current_locale]){
el = eval("I18n['"+current_locale+"']." + key);
}
if(window.I18n[default_locale] && typeof(el) == 'undefined'){
el = eval("I18n['"+default_locale+"']." + key);
}
if(typeof(el) == 'undefined'){
el = key;
}
return el;
};
views / layout / application.html.erb
...
<%= javascript_tag "var current_locale = '#{I18n.locale.to_s}';" %>
<%= javascript_tag "var default_locale = '#{I18n.default_locale}';" %>
...
자바 스크립트 코드에서 다음과 같이 번역 할 수 있습니다.
// current_locale:fr , default_locale:en
// existing translation (in french)
I18n.t('message.hello_world'); // => Bonjour le monde
// non-existing translation (in french) but existing in english
I18n.t('message.hello_this_world'); // => Hello this world
// non-existing translation (french & english)
I18n.t('message.hello_this_new_world'); // => message.hello_this_new_world
도움이 되길 바랍니다!
Ryan 솔루션은 화려합니다. 전체 파일을 포함하지 않도록하지만 당신은 사용해야 @translations[I18n.locale].with_indifferent_access["alpha"]
하는 대신I18n.backend.send(:translations)["alpha"]
I18n-js 는 저에게 잘 작동하며 추천합니다. 그의 재 작성 브랜치 를 사용하는 경우 플러그인에는 /assets/i18n/filtered.js
수동으로 아무것도 할 필요없이 @ ryan-montgomery가 대답 한 것을 정확히 출력 하는 파일 이 포함 됩니다.
This way, you can use the same translations on the backend with Rails helpers t(:key)
and using I18n.t('key')
in Javascript on the frontend.
For applications like the one you described "that does not support Internationalization at all" and "is too late to fix it now" I wrote a very quick approach: the jQuery plugin Quick-i18n: https://github.com/katio/Quick-i18n demo (and how to use it): http://johannpaul.net/Quick-i18n/
ReferenceURL : https://stackoverflow.com/questions/2701749/rails-internationalization-of-javascript-strings
'Nice programing' 카테고리의 다른 글
"pull to refresh"작업을 비활성화하고 표시기 만 사용하는 방법은 무엇입니까? (0) | 2021.01.05 |
---|---|
VB.NET에서 배열을 인라인으로 선언하는 방법 (0) | 2021.01.05 |
SQL 삽입 문에서 비트 값을 반전하는 우아한 방법이 있습니까? (0) | 2021.01.05 |
정적 열거 형, C # 선언 문제 (0) | 2021.01.05 |
Haskell에서 언제 let과 함께 사용합니까? (0) | 2021.01.05 |