简体   繁体   English

Rails Json具有多语言响应

[英]Rails Json with Multilanguage response

I have a Controller that has a mobile client, the response currently are in English, however im questioning if there's a way to customize the language of the response. 我有一个具有移动客户端的Controller,响应当前为英语,但是我在质疑是否有一种自定义响应语言的方法。

Ex: 例如:

English: { "success": false, "message": "Error with your login or password" } 英语:{“成功”:false,“消息”:“您的登录名或密码错误”}

Spanish:{ "success": false, "message": "Error con tu usuario o contraseña" } 西班牙语:{“成功”:false,“消息”:“错误使用注意事项”}

and of curse the content of the "message" is gonna be located in the language configuration file that rails has: 并且诅咒“消息”的内容将位于rails具有的语言配置文件中:

en.yml en.yml

or 要么

es.yml es.yml

and this is the function where the response is generated. 这就是生成响应的功能。

def invalid_login_attempt
    warden.custom_failure!
    render :json => { :success => false, :message=> "Error with your login or password" }, :status => 401
  end

Thanks. 谢谢。

Have you tried I18n.t ? 您尝试过I18n.t吗?

render :json => { :success => false, :message=> I18n.t('your_key') }, :status => 401

And you can set the locale for every request in ApplicationController based on some criteria, like for example 而且您可以根据一些条件为ApplicationController的每个请求设置语言环境,例如

before_action :set_locale

def set_locale
  I18n.locale = request.headers["X-Lang"] || I18n.default_locale
end

Setting up internationalization (I18n) for Rails should be pretty much the same for HTML and JSON responses. 为Rails设置国际化(I18n)对于HTML和JSON响应应该几乎相同。 Have a look at the official tutorial . 看一下官方教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM