1

我一直在考虑这个问题,但我无法弄清楚构建我的功能的步骤:

我有一个像 html 数据作为输入的小问题,这个结构由 html 和自定义元素组成,例如:

格式:[标签名称选项和正文]

[:a {} []] ;; simple
[:a {} [[:span {} []]]] ;; nested component
[:other {} []] ;; custom component at tag-name
[:a {} [[:other {} []]]] ;; custom component at body

每次结构有一个自定义元素时,我都应该用 html 表示来渲染(替换)它database,自定义元素可能出现在tag-namebody中:

(def example
  [:div {} [[:a {} []]
            [:custom {} []]]])

    (def database {
      :custom [[:a {} []
               [:div {} []]})

(def expected-result
  [:div {} [[:a {} []]
            [:a {} []]
            [:div {} []]]])

问题是:如何创建一个获取此数据的函数,查找组件的标签和主体,如果有自定义元素将其替换为database元素,替换后再次查看,如果有新组件执行此操作又迈出一步……

我已经有一个函数(custom-component?),它接受一个标签名称并返回一个布尔值,如果是一个自定义元素:

(custom-component? :a) ;; false
(custom-component? :test) ;; true

感谢您的帮助,我真的坚持这一点。

4

1 回答 1

4

clojure 有一种特殊的方式来完成这项任务 - 拉链:http: //josf.info/blog/2014/03/28/clojure-zippers-structure-editing-with-your-mind/

这是您的问题解决方案的一个粗略示例(我在您的database.

(require '[clojure.zip :as z])

(def example
  [:div {} [[:custom2 {} []]
            [:a {} []]
            [:custom {} []]]])

(def database {:custom [[:a {} []]
                        [:div {} [[:custom2 {} [[:p {} []]]]]]]
               :custom2 [[:span {} [[:form {} []]]]]})

(defn replace-tags [html replaces]
  (loop [current (z/zipper
                  identity last
                  (fn [node items]
                    [(first node) (second node) (vec items)])
                  html)]
    (if (z/end? current)
      (z/root current)
      (if-let [r (-> current z/node first replaces)]
        (recur (z/remove (reduce z/insert-right current (reverse r))))
        (recur (z/next current))))))

在回复中:

user> (replace-tags example database)
[:div {} [[:span {} [[:form {} []]]] 
          [:a {} []] 
          [:a {} []] 
          [:div {} [[:span {} [[:form {} []]]]]]]]

但要注意:它不会计算替换内部的周期,所以如果你有这样的循环依赖:

(def database {:custom [[:a {} []]
                        [:div {} [[:custom2 {} [[:p {} []]]]]]]
               :custom2 [[:span {} [[:custom {} []]]]]})

它会产生一个无限循环。

于 2016-03-27T08:49:27.850 回答