Phoenix Framework-每个路线的页面标题 [英] Phoenix Framework - page titles per route

查看:62
本文介绍了Phoenix Framework-每个路线的页面标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Phoenix框架中,有一种基于路由/路径来设置页面标题的通用技术.还是仅仅是在路由函数内的正确位置调用 assign(:page_title,"fred")的问题?

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") at the right point inside my routed function?

更新

我最终实现了@michalmuskala解决方案的一种变体.我忽略了动作名称,而不是 @view_template :

I ended up implementing a variation of @michalmuskala's solution. I pass up the action name instead of @view_template:

<title><%= @view_module.title(action_name(@conn), assigns) %></title>

然后在视图模块中,代码如下所示:

Then in the view module the code looks like this:

def title(:show, assigns), do: assigns.user.name <> " (@" <> assigns.user.user_name <> ")"
def title(:edit, _assigns), do: "Edit Profile"
def title(_action, _assigns), do: "User related page"

以上代码中的最后一条语句是该模块的可选全部捕获"(这是我可能仅在过渡时会做的事情)

The last statement in the above code is an optional "catch all" for the module (and is something I'll probably only do while transitioning)

推荐答案

处理标题的一种好方法是认识到视图是一个与其他模块一样的模块.这意味着您可以在其上定义其他功能.另一方面,在布局中您可以访问当前的视图模块-这意味着我们可以调用我们之前定义的函数.

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
<title><%= @view_module.title(@view_template, assigns) %></title>

# In some view module
def title("show.html", _assigns) do
  "My awesome page!"
end

由于同时传递了模板名称和赋值给title函数,它的工作原理与 render/2 完全一样-我们可以在模板名称上进行模式匹配,并可以访问所有赋值.我们在所有视图上无条件调用该函数,因此必须在所有视图上定义该函数-我们可以使用 function_exported?/3 和一些默认的后备标题添加一些附加检查,但是我认为明确并在每个视图中定义它并不需要太多工作,并且可以简化代码.

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.

这篇关于Phoenix Framework-每个路线的页面标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆