0
有很多的Ruby寶石做什麼,我想在藥劑:globalize,multilang-hstore,hstore_translate如何包裝Ecto hstore字段以自動獲取翻譯?
如何自動化例如使用Gettext.get_locale
根據hstore字段中的當前語言環境檢索翻譯?例如,如果我通過相關帖子post.tags
得到它,則區域設置爲:en:"tags: ["climbing", "ski"]"
而不是"tags":[{"name":{"pl":"narty","en":"ski"}},{"name":{"pl":"wspinaczka","en":"climbing"}}]
的標記將包含一個字符串列表?如何處理Gettext的後備?
defmodule Myapp.Tag do
use Myapp.Web, :model
schema "tags" do
field :name, :map
belongs_to :post, Myapp.Post
timestamps
end
def match(query, q) do
from tag in query,
where: fragment("?->>? ILIKE ?", tag.name, "en", ^(String.downcase(q) <> "%"))
end
end
defmodule Myapp.TagController do
use Myapp.Web, :controller
alias Myapp.Tag
def search(conn, %{"q" => q}) do
tags = Tag |> Tag.match(q) |> Repo.all
render(conn, "options.json", tags: tags)
end
end
defmodule Myapp.TagView do
use Myapp.Web, :view
def render("options.json", %{tags: tags}) do
%{options: render_many(tags, Myapp.TagView, "option.json")}
end
def render("option.json", %{tag: tag}) do
%{id: tag.id,
value: tag.name["en"],
label: tag.name["en"]}
end
end
defmodule Myapp.PostView do
use Myapp.Web, :view
def render("posts.json", %{posts: posts}) do
%{data: render_many(posts, Myapp.PostView, "post.json")}
end
def render("post.json", %{post: post}) do
%{id: post.id,
title: post.title,
tags: post.tags} # <= how to get translated keys
end
end
謝謝,你能告訴我如何通過相關的'post.tags'在Myapp.PostView渲染函數中獲取它們,如何翻譯列表中的所有鍵?我可以在默認情況下爲每個標籤提取自動執行嗎?假設沒有管道操作員? – leon
如果要將某些操作應用於元素列表,可以使用映射。 'Enum.map(list,translate_key)'。你可以添加功能到你的模型。在從Ecto中獲取東西並在您的視圖中使用它之後進行翻譯。 – tkowal