2015-12-10 20 views
2

我有一些客戶端靜態jQuery代碼,我想用我的網站的每個頁面上使用的服務器動態代碼替換,並取決於我的頁面在(被問路線)。 我現有的jQuery代碼(模板html.eex文件):Phoenix:在視圖中使用「conn」和「case」

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 

什麼是這樣做的權利的最佳途徑? (我也不確定「案例」代碼)。

回答

8

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

請靈藥注意,功能應該是snake_case而不是camelCase

在函數中使用case是很好的,除非在路徑和結果之間有明確的映射。如果你只是想刪除領先"/"那麼你可以這樣做:

iex(3)> String.slice("/page1", 1..-1) 
"page1"