Switching between 2 or more patterns with action in controllers?

I have a default Phoenix app. This application will have a page_controller which will load the index.html.eex file.

An application will know to use view to access templates/page/index.html.eex .

Now say that you created another html page that is identical to index.html.eex in every way, except in French.

Since we do not want to create a completely new Phoenix application that will have all the same code, except that the French translation of the current page/index.html.eex , there is a way to tell the view or controller whose file you need to download.

Is there a plug that can be placed on the router to change where render will look for its patterns?

+5
source share
2 answers

First of all, I suggest you use Gettext to use labels for French pages.

For example, you can use all French templates in the same folders (so as not to change the logic for the presentation), but call them a suffix, for example. "index_fr.html.eex", etc., and then you can write a fairly simple helper (not necessarily a plug-in) that will add this suffix to all your templates.

However, I would recommend that you use Gettext - the source code of the template is only in place, and almost all Gettext logic processes you.

0
source

I suggest you choose @patnowak's answer. Use Gettext that the tool is made for translation and powerful enough.

If you still want to do this, remember render/3 in the controller calls the render/2 functions defined in the views, if defined. If not, it performs the default rendering function and looks for the template. Read the docs for more details.

So, for example, this is a controller:

 def index(conn, params) do # defined assigns as you wish render(conn, "index.html", assigns) end 

Now define this in the view:

 def render("index.html, assigns) do case assigns[:lang] do "fr" -> render("index_fr.html", assigns) _others -> render("index_en.html", assigns) end end 

You can also write a plug-in that automatically puts :lang in the assignment:

 def lang_plug(conn, opts) do conn |> fetch_query_params() |> (fn cn -> assign(cn, :lang, cn.query_params[:lang] || "en").() end 

Take a look at Plug.Conn for documents fetch_query_params/1 and assign/3 , as well as other functions for extracting a language from other places, such as: headers or bodies.

You get the idea. In a cork, fill assigns :lang , extracts them inside your specific rendering function, and acts accordingly.

However, do not do this. Using gettext is the right way.

0
source

Source: https://habr.com/ru/post/1270343/


All Articles