views:

926

answers:

1

I found a very basic web page on the Internet and now I would like to do the obvious thing and add some CSS so I can build nicer pages.

  1. How can I include jQuery, as well as other style sheets?
  2. How can I include inline CSS so I can throw in a text-align: center, for example, to try out quick changes?

Regular jQuery include:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"/>

Basic Hello World server without formatting: (Updated to include static routing fix so others will be up and running quicker)


(ns hello-world
  (:use compojure))

(defn index
  [request]
    (html
    [:h1 "Hello World"]
    [:p "This is ugly with CSS!"])
    )

(defn hello
  [request]
  (html ""
   [:title "A very long title"]
   [:div.comment
    [:h1 "Hello's Page"]
    [:p "This would look better with some CSS formatting!"]]
))

(defroutes greeter
  (GET "/" index)
  (GET "/h" hello)
  (GET "/*"
       (or (serve-file "/opt/compojure/www/public" (params :*)) ;; This is needed to find CSS and js files
       :next))
  (ANY "*"
       (page-not-found) ;;  404.html is in /opt/compojure/www/public/404.html
  ))


(run-server {:port 9090}
  "/*" (servlet greeter))

+8  A: 

You can include style attributes to assign your 'inline css styles' using syntax like:

[:h1 {:style "background-color: black"} "Hello's Page"]

You can also include a stylesheet tag and javascript using the include-css and include-js functions.

(defn hello
  [request]
  (html ""
   [:html
     [:head
        [:title "A very long title"]
        (include-css "my css file")
        (include-js "http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js")]
     [:body
       [:div.comment
          [:h1 "Hello's Page"]
          [:p "This would look better with some CSS formatting!"]]]]))

In order to serve static files like css and js files you will need to change your route statement slightly and add something like:

   (GET "/*"
    (or (serve-file "PATH_TO_FILES" (params :*)) :next))

otherwise, your local css file will never get served.

Joshua Smith
I've tried both (include-css "style.css") and (include-css "/style.css") but I get a 404. style.css is in the same directory as my hello.clj.
Yes, I needed to handle static files with the GET "/*" ... http://en.wikibooks.org/wiki/Compojure/Tutorials_and_Tips