Phoenix:在视图中使用 "conn" 和 "case"
Phoenix: using "conn" and "case" in a view
我有一些客户端静态 jQuery 代码,我想将其替换为我网站每个页面上使用的服务器动态代码,具体取决于我所在的页面(被询问的路线) ).
我现有的 jQuery 代码(在模板 html.eex 文件中)是:
if (SOME CONDITION) {
$(".page1.firstChild").css({"margin-top": "70px"});
$(".page2.firstChild").css({"margin-top": "70px"});
$(".page3.firstChild").css({"margin-top": "70px"});
$(".page4.firstChild").css({"margin-top": "70px"});
} else {
$(".page1.firstChild").css({"margin-top": "0px"});
$(".page2.firstChild").css({"margin-top": "0px"});
$(".page3.firstChild").css({"margin-top": "0px"});
$(".page4.firstChild").css({"margin-top": "0px"});
}
所以,我想将“.page1
”、“.page2
”、...“.pageN
”替换为使用 [=18 放置在模板中的变量=] 并在我的 layout_view 中定义,以便在与该布局相关的每个页面上都可以访问它。所以我尝试了这个:
defmodule myApp.LayoutView do
use myApp.Web, :view
def currentPage do
case @conn.request_path do
"/page1" -> "page1"
"/page2" -> "page2"
"/page3" -> "page3"
end
end
end
我收到这个错误:
undefined function: nil.request_path/0
正确执行此操作的最佳方法是什么? (我也不确定 "case" 代码)。
@conn
在您的模板中可用,因为它通过 assigns
.
传递
但是您不能定义函数并使它可用。它需要作为参数传递给您的函数:
defmodule myApp.LayoutView do
use myApp.Web, :view
def current_page(conn) do
case conn.request_path do
"/page1" -> "page1"
"/page2" -> "page2"
"/page3" -> "page3"
end
end
end
您可以通过以下方式从您的模板中调用它:
current_page(@conn)
请注意在 elixir 中,函数应该在 snake_case
而不是 camelCase
。
在函数中使用 case
没问题,除非路径和结果之间有明确的映射。如果您实际上只想删除前导 "/"
那么您可以这样做:
iex(3)> String.slice("/page1", 1..-1)
"page1"
我有一些客户端静态 jQuery 代码,我想将其替换为我网站每个页面上使用的服务器动态代码,具体取决于我所在的页面(被询问的路线) ). 我现有的 jQuery 代码(在模板 html.eex 文件中)是:
if (SOME CONDITION) {
$(".page1.firstChild").css({"margin-top": "70px"});
$(".page2.firstChild").css({"margin-top": "70px"});
$(".page3.firstChild").css({"margin-top": "70px"});
$(".page4.firstChild").css({"margin-top": "70px"});
} else {
$(".page1.firstChild").css({"margin-top": "0px"});
$(".page2.firstChild").css({"margin-top": "0px"});
$(".page3.firstChild").css({"margin-top": "0px"});
$(".page4.firstChild").css({"margin-top": "0px"});
}
所以,我想将“.page1
”、“.page2
”、...“.pageN
”替换为使用 [=18 放置在模板中的变量=] 并在我的 layout_view 中定义,以便在与该布局相关的每个页面上都可以访问它。所以我尝试了这个:
defmodule myApp.LayoutView do
use myApp.Web, :view
def currentPage do
case @conn.request_path do
"/page1" -> "page1"
"/page2" -> "page2"
"/page3" -> "page3"
end
end
end
我收到这个错误:
undefined function: nil.request_path/0
正确执行此操作的最佳方法是什么? (我也不确定 "case" 代码)。
@conn
在您的模板中可用,因为它通过 assigns
.
但是您不能定义函数并使它可用。它需要作为参数传递给您的函数:
defmodule myApp.LayoutView do
use myApp.Web, :view
def current_page(conn) do
case conn.request_path do
"/page1" -> "page1"
"/page2" -> "page2"
"/page3" -> "page3"
end
end
end
您可以通过以下方式从您的模板中调用它:
current_page(@conn)
请注意在 elixir 中,函数应该在 snake_case
而不是 camelCase
。
在函数中使用 case
没问题,除非路径和结果之间有明确的映射。如果您实际上只想删除前导 "/"
那么您可以这样做:
iex(3)> String.slice("/page1", 1..-1)
"page1"