来自html文件的Clojurescript模板

时间:2014-05-20 18:52:31

标签: clojurescript

我是clojure / clojurescript的新手,所以我可以忽略一个简单的解决方案,但这是我的问题:

我有现有的html文件(只是原始的html,没有变量或任何东西)我想用作clojurescript项目的部分(这些html文件是导航,页脚等)。我想在clojurescript项目中要求这些html模板,然后在编译的js中内联模板,这样我就不必对生产中的模板进行任何ajax调用或复制html文件在生产中可供客户使用。像requirejs和browserify这样的项目有插件让你只需要' html文件 - 是否有clojurescript的等价文件?

我知道要进行模板/ dom操作的库,所以这不是问题。它只是将多个外部html文件转换为内联字符串/ dom节点/生产js中包含的内容。

由于

1 个答案:

答案 0 :(得分:7)

您可以使用在编译时执行的宏来执行此操作。

<强> project.clj

  :dependencies [[org.clojure/clojure "1.6.0"]
                 [org.clojure/clojurescript "0.0-2202"]]
  :source-paths ["src"]
  :cljsbuild
  {:builds
   [{:id "main"
     :source-paths ["src/cljs"]
     :compiler
     {
      :output-to "resources/main.js"
      :optimizations :whitespace
      :pretty-print true}}]})

的src / cljstemplates / core.clj

(ns cljstemplates.core
  (:require [clojure.java.io :refer (resource)]))

(defmacro deftmpl
  "Read template from file in resources/"
  [symbol-name html-name]
  (let [content (slurp (resource html-name))]
    `(def ~symbol-name
       ~content)))

<强>的src / cljs / web.cljs

(ns cljstemplates.web
  (:require-macros [cljstemplates.core :refer [deftmpl]]))

(deftmpl head "header.html")
(deftmpl nav "nav.html")
(deftmpl foot "footer.html")

这将生成包含从资源/文件夹中的文件读取的字符串的变种headnavfoot

<强>资源/ nav.html

<nav>
  <ul>
    <li>Tweets</li>
  </ul>
</nav>

输出(main.js):

cljstemplates.web.nav = "\x3cnav\x3e\n  \x3cul\x3e\n    \x3cli\x3eTweets\x3c/li\x3e\n  \x3c/ul\x3e\n\x3c/nav\x3e\n";