Phoenix Framework - page titles per route

后端 未结 1 1862
臣服心动
臣服心动 2021-02-15 12:05

In the Phoenix Framework is there a common technique for setting a page title based on a route/path. Or is this just a matter of calling assign(:page_title, \"fred\")

1条回答
  •  天涯浪人
    2021-02-15 12:43

    A nice approach to handling titles is to realise that view is a module like every other one. This means you can define additional functions on it. On the other hand, in the layout you have access to the current view module - this means we can call the function we defined earlier.

    Let's see how that would work in practice:

    # The layout template
    <%= @view_module.title(@view_template, assigns) %>
    
    # In some view module
    def title("show.html", _assigns) do
      "My awesome page!"
    end
    

    Thanks to passing both template name and assigns to the title function it works exactly like render/2 - we can pattern match on the template name and have access to all the assigns. We're calling the function unconditionally on all the views, so it has to be defined on all the views - we could add some additional check with function_exported?/3 and some default fallback title, but I think being explicit and defining it in every view isn't that much work and makes for a simpler code.

    0 讨论(0)
提交回复
热议问题