2016-03-06 37 views
1

我是clojure和compojure的新手,並嘗試使用ring和compojure創建基本的Web應用程序。從compojure服務index.html文件

這裏是我的handler.clj

(ns gitrepos.handler 
    (:require [compojure.core :refer :all] 
      [compojure.route :as route] 
      [ring.util.response :as resp] 
      [ring.middleware.defaults :refer [wrap-defaults site-defaults]])) 

(defroutes app-routes 
    (GET "/" [] (resp/file-response "index.html" {:root "public"})) 
    (route/not-found "Not Found")) 

(def app 
    (wrap-defaults app-routes site-defaults)) 

我有這個的index.html/資源/公共文件,但應用程序不渲染這個HTML文件。反而變得找不到

我已經搜查了很多它,即使這個Serve index.html at/by default in Compojure似乎並沒有解決問題。

不知道我在這裏錯過了什麼。

回答

0

也許你想嘗試使用一些模板庫,如Selmer。所以,你可以做這樣的事情:

(defroutes myapp 
    (GET "/hello/" [] 
    (render-string (read-template "templates/hello.html")))) 

或者經過一定的價值:

(defroutes myapp 
    (GET "/hello/" [name] 
    (render-string (read-template "templates/hello.html") {name: "Jhon"}))) 

而且,正如@ piotrek-Bzdyl說:

(GET "/" [] (resource-response "index.html" {:root "public"})) 
+0

這似乎更好的選擇,嘗試clostache,它的工作,謝謝。 – navyad

+0

不錯!是的,clostache也是一種選擇 – elf

1

Naveen

這是我自己的片段似乎工作。在與你比較,你沒有資源路徑defroutes

(defroutes default-routes 
    (route/resources "public") 
    (route/not-found 
    "<h1>Resource you are looking for is not found</h1>")) 

(defroutes app 
    (wrap-defaults in-site-routes site-defaults) 
    (wrap-defaults test-site-routes site-defaults) 
    (wrap-restful-format api-routes) 
    (wrap-defaults default-routes site-defaults)) 
-1

你不需要指定路由使用file-response於這個目錄下將送達感謝site-defaultsresoures/public投放文件。您唯一缺少的部分是將/路徑映射到/index.html,這可以使用您從另一個問題中提到的代碼完成。因此,解決辦法是:

(defn wrap-dir-index [handler] 
    (fn [req] 
    (handler 
     (update 
     req 
     :uri 
     #(if (= "/" %) "/index.html" %))))) 

(defroutes app-routes 
    (route/not-found "Not Found")) 

(def app 
    (-> app-routes 
    (wrap-defaults site-defaults) 
    (wrap-dir-index) 

在一個側面說明,你應該更喜歡使用ring.util.response/resource-response,因爲它提供來自類路徑的文件,並且還將工作時,你的應用程序包,你到一個jar文件。 file-response使用文件系統來查找文件,並且不會從jar文件中運行。

+0

能否downvoter解釋什麼是錯我的答案?如果我知道爲什麼它是錯誤的,我將非常樂意修復它或刪除它。 –

相關問題