gpt4 book ai didi

elixir - Phoenix : using "conn" and "case" in a view

转载 作者:行者123 更新时间:2023-12-02 06:31:44 25 4
gpt4 key购买 nike

我有一些客户端静态 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”替换为使用 <% currentPage %> 放置在模板中的变量。并在我的 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

正确执行此操作的最佳方法是什么? (我也不确定“案例”代码)。

最佳答案

@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"

关于elixir - Phoenix : using "conn" and "case" in a view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34210447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com