不能 eval/load-string 从字符串 clojure 函数

Can't eval/load-string clojure function from string

我需要从 edn 文件中读取一个 clojure 函数,该文件输出 hiccup 以生成 html 内容。 但是我被困在需要评估功能的部分。 我收到错误消息:

java.lang.RuntimeException: Unable to resolve symbol: fn in this context, compiling:(null:1:1)

((eval (read-string "(fn [] (list [:div\"Hello\"]))")))

((load-string "(fn [] (list [:div\"Hello\"]))"))

在 clojure REPL 中工作并输出预期结果

([:div "Hello"])

project.clj

(defproject infocenter "0.1.0-SNAPSHOT"
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [org.clojure/clojurescript "1.9.225"]
                 [hiccup "1.0.5"]]
  :plugins [[lein-figwheel "0.5.4-7"]]
  :clean-targets ^{:protect false} [:target-path "out" "resources/public/cljs"]
  :cljsbuild {
              :builds [{:id "dev"
                        :source-paths ["src"]
                        :figwheel true
                        :compiler {:main "templ.core"
                                   :asset-path "cljs/out"
                                   :output-to  "resources/public/cljs/main.js"
                                   :output-dir "resources/public/cljs/out"}}]}
  :figwheel {
             :css-dirs ["resources/public/template"]})

core.cljs

(ns templ.core
  (:require-macros [templ.edn :refer [read-edn]]))
(let [div (. js/document getElementById "content")]
     (set! (. div -innerHTML) (read-edn "fn.edn")))

edn.clj

(ns templ.edn
  (:use [hiccup core form]))

(defmacro read-edn
  "Read template from file in resources/"
  [edn-name]
  ;(slurp edn-name)
  ;((eval (read-string "(fn [] (list [:div\"Hello\"]))")))
  ((load-string "(fn [] (list [:div\"Hello\"]))"))
  )

试试这个:

(ns xyz.core
  (:gen-class))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "main - enter")
  (println (eval '(+ 2 3)))
  (println ((eval (read-string "(fn [] (list [:div\"Hello\"]))"))))
  (println "main - exit")
)

结果:

> lein run
main - enter
5
([:div Hello])
main - exit

这只是普通的 Clojure,我看到您也在使用 CLJS。您的 CLJS 部分设置可能存在一些问题。你想用 read-ednfn.edn 做什么?我会尽可能完全避免使用宏。