I'm trying to put a simple site together to demonstrate a ClojureScript library with a couple of "pages", each of which contains several examples.
I used a leiningen template to make a project with devcards, routing etc.
I now have the default boilerplate :
(defn home-page []
[:div [:h2 "Welcome to site"]
[:div [:a {:href "/about"} "go to about page"]]] )
(defn about-page []
[:div [:h2 "About site"]
[:div [:a {:href "/"} "go to the home page"]]])
I now want to put some devcards into these "pages".
However, just putting a defcard either next to or inside one of these functions doesn't seem to add it to the page.
So can devcards be used in this context? If so, where / how do I put them?
Related
I want to access the current page URL in my Selmer templates so that I can pass it to an edit page action so that this page can include a link back to the 'calling' page even after editing.
Here's the template code in my Selmer template -- this seems OK:
<a href="/photos/_edit/{{p.path}}{% if back %}?back={{back}}{% endif %}"
class="btn btn-warning btn-sm">edit</a>
Here's how I set the back value when searching:
(defn photo-search [word req]
(layout/render
"search.html"
{:word word
:photos (db/photos-with-keyword-starting word)
:back (str (:uri req) "?" (:query-string req))
}))
;; ...
(defroutes home-routes
;; ...
(GET "/photos/_search" [word :as req] (photo-search word req))
This works OK. However I have other methods that return lists of photos, and it seems to violate the DRY principle to add this code to all other methods.
Is there an easier way to do this, maybe with some middleware?
One approach you could try is creating your own render function that wraps selmer's and provides the common functionality you want on every page. Something like:
(defn render
[template request data]
(let [back (str (:uri req) "?" (:query-string req))]
(layout/render template (assoc data :back back))))
(defroutes home-routes
(GET "/photos/" [:as req]
(->> {:photos (db/recent-photos)}
(render "list.html" req)))
(GET "/photos/_search" [word :as req]
(->> {:word word
:photos (db/photos-with-keyword-starting word)}
(render "search.html" req))))
(For some reason I really like using threading macros in routes, even though their arguably aren't enough links in the thread to justify it...)
In my Reagent project, I'm parsing HTML with Hickory and rendering a Hiccup page. The hiccup is rendered. But when I change the page (!reset my view atom), React.js goes crazy because Hickory has generated:
[:div (as-hiccup (parse "<h1>HELLO WORLD!</h1>"))]
=> ([:html {} [:head {}] [:body {} [:h1 {} HELLO WORLD!]]])
As you can see, it has generated <html> <head> <body> tags which I think is causing Reactjs to blow up because my view already have those tags. Ideally, I want it to only generate [:h1 {} HELLO WORLD!]
(map as-hiccup (parse-fragment "<h1>HELLO WORLD!</h1>"))
generates [:h1 "HELLO WORLD!"]
I'm trying to do something simple with Clojure Enlive lib: I want the top menu of my page to be different based on language selected by the user (English or Japanese). I can't find how to implement this basic feature.
I have a "template/header.html" template with 2 sections (one per language):
<div class="header en-US">...</div>
<div class="header ja-JP">...</div>
I created 2 corresponding snippets in my templating code:
(:require [net.cgrand.enlive-html :as html])
...
(html/defsnippet header-ja-JP "templates/header.html" [:div.header.ja-JP] [])
(html/defsnippet header-en-US "templates/header.html" [:div.header.en-US] [])
Now when I load my main template (index.html) I want to populate my header menu code into my nav tag.
Below, the argument 'lang' value is either "en-US" or "ja-JP":
(defn process-template
[lang]
(let [header-selector (str “header-“ lang)
header-content (#(resolve (symbol header-selector)))]
(apply str
(html/emit*
(html/at
(html/html-resource "templates/index.html")
[:nav] (html/content (header-content)))))))
It throws a java.lang.NullPointerException
If I replace the last line by
[:nav] (html/content (header-ja-JP)))))))
or
[:nav] (html/content (header-en-US)))))))
it works fine (so the snippets work), but I've tried lots of different syntaxes and can't make the dynamic header work based on language.
The above code (let part) seems ok if I execute it manually in REPL, the header-content is JSON object containing the correct content so I don't understand why I get a NullPointerException.
Ideally I think I should have only one snippet taking the language as argument and returning the corresponding HTML section, but didn't manage to do that either.
I'm very new at Clojure so I'm probably missing something obvious here; if someone could point me to what's wrong in the code above or another way to make this work that will be awesome.
Thanks,
Olivier
If we want to do it differently as cgrand suggests, there are many, many ways to accomplish this. I have a hard time imagining how he'd do it with maps, but I'd do it this way:
(defn process-template [lang]
(html/select (html/html-snippet
"<html>
<head></head>
<body>
<nav>
<div class=\"en\"></div>
<div class=\"jp\"></div>
</nav>
</body>
</html>")
[(keyword (str "div." lang))]))
(apply str (html/emit* (process-template "en")))
=> "<div class=\"en\"></div>"
Of course read it from file instead of HTML in a string. The function plucks out the matching HTML node according to a selector.
Your (#(resolve (symbol header-selector))) returns a value.
(resolve (symbol header-selector)) returns a function.
[:nav] (html/content (header-content))))))) calls header-content as a function.
Replace (#(resolve (symbol header-selector))) with (resolve (symbol header-selector)).
I'm fuzzy on what html/at and html/html-resource do so if other problems crop up you might need to cram in clojure.java.io/file in there.
I have never done any kind of web programming before so I have no idea what I need to do to get this Clojure app I wrote to run on live server. The url of my page is http://rowdy.msudenver.edu/~jnels124/. Here is my Clojure code
(ns startingclojure.core
(:use (compojure handler[core :only (GET POST defroutes)])
[clojure.pprint])
(:require [net.cgrand.enlive-html :as en]
[ring.util.response :as response]
[ring.adapter.jetty :as jetty]))
(defonce counter (atom 10000))
(defonce urls (atom {}))
( defn shorten
[url]
(let [id (swap! counter inc)
id (Long/toString id 36)]
(swap! urls assoc id url)
id))
(en/deftemplate homepage
(en/xml-resource "homepage.html")
[request]
[:#listing :li]
(en/clone-for [[id url] #urls]
[:a] (comp ;; comp composes any number of functions
(en/content (format "%s : %s" id, url))
(en/set-attr :href (str \/ id)))))
(defn redirect
[id]
(response/redirect (#urls id)))
(defroutes app*;; * ususally means implementation detail or lower level operation
(GET "/" request (homepage request))
(POST "/shorten" request
(let [id (shorten (-> request :params :url))]
(response/redirect "/")))
(GET "/:id" [id] (redirect id)))
(def app (compojure.handler/site app*))
Here is the html
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
</head>
<body>
<form method="POST" action="/shorten">
<input type="text" name="url"/>
<input type="submit" value="Shorten!"/>
</form>
<ul id="listing">
<li>
id :url
</li>
</ul>
</body>
</html>
So here are the actual questions I have.
How do I get the Clojure to execute on the server. I have been loading this code in the repel and starting with (def server(jetty/run-jetty #'app {:port 8080 :join? false}))?
Also, what is the correct way to bring this project into view(i.e file structure). The file structure on the server is just
Top level: bin public_html
in public_html is cgi-bin index.html startingclojure(my app, from tutorial)
in index html is what you see when that page is entered and startingclojure has the leiningen file structure.
I am not sure if I have provided the all of the necessary information but I am happy to provide anything you may need to help me get started. Thanks in advance.
Running lein, or even a repl, on a production box is a bad idea.
You should define a -main function that creates and runs your web server process if you execute lein run locally. Then, when you are ready to deploy, run lein uberjar to create a jar containing your entire app and all its dependencies. Once you have that jar file on the server, you can run it via java -jar my-app.jar. You will probably want a script that also sets up all the right java execution variables and the port it should run on etc. (these can be provided on the command line and are passed in as strings to -main).
If the app requires certain files to be unpacked, you will need to extract the jar (or at least that part of the jar) and make sure the app process can find it at runtime. A jar is a zip file, and can be extracted with the unzip command from the command line. If you need to refer to resources that are still inside the jar for reading, you should replace any references to clojure.java.io.file (or native java File objects) with clojure.java.io/resource.
It will probably take a while to work out all these inter-environment differences, but luckily each of these steps can be tested locally as you refine them.
I've been converting some Noir websites to Compojure.
I have a function here that creates the layout of the page:
(defn layout [title & content]
(html5
[:head
[:title "My Site | " title]
(include-css "css/main.css")
[:body
[:header
[:h1 (link-to "/" "My Site")]]
content]))
And this is the function and the routes:
(defn home-page []
(layout
"Home"
[:div [:p "Home Page"]])))
(defn article-list []
(layout
"Article List"
[:div [:p "Article List"]])))
(defroutes app-routes
(GET "/" [] (home-page))
(GET "/article-list" [] (article-list))
When I open up localhost:3000/article-list all of the CSS rules work fine.
However, when I attempt to extend the URL path and change the program to:
(defn article-list []
(layout
"Article List"
[:div [:p "Article List"]])))
(defn article-one []
(layout
"Article One"
[:div [:p "Article One"]])))
(defroutes app-routes
(GET "/" [] (home-page))
(GET "/article-list" [] (article-list)
(GET "/article-list/article-one" [] (article-one))
And go to localhost:3000/article-list/article-one, I get all of the HTML but the CSS rules no longer work. When I inspect the page, the css paths are included in the < head > element but there are no styles on the page.
I've searched for a solution to this issue, but there doesn't seem to be any writing on this. I've also tried pulling out the routes so that I have:
(defroutes article-routes
(GET "/article-list/article-one" [] (article-one))
(defroutes app-routes
(GET "/" [] (home-page))
(GET "/article-list" [] (article-list)
(context "article-list" [] article-routes)
but I have the same issue. How can I get the CSS rules to work on pages with extended paths?
Your CSS is being included with a relative path, which means the when you go to localhost:3000/article-list/article-one your browser is looking for the CSS at localhost:3000/article-list/css/main.css.
The easiest way to fix this would be to include the CSS with (include-css "/css/main.css"). The / at the beginning will ensure it always searches for localhost:3000/css/main.css.