用于简单字符串模板的轻量级 Clojure 库?
Lightweight Clojure library for simple string templating?
我正在寻找一个(最好是小的)Clojure 库,它在 clojars 中可用,它允许我替换字符串中的简单模板,例如:
"Hello my name is ${name}"
其中 ${name}
应由模板引擎替换。在 Java 中,我通常使用完美的 JMTE。我知道我也可以从 Clojure 中使用它,但我想知道是否有比 Clojure 更多的东西 friendly/idiomatic.
我找到了 this。
也许这就是您要找的。
有很多模板库。一些通用的是:
注意:如果您只需要一些巧妙的格式化,您可以使用带有 cl-format
函数的标准库 clojure.pprint 和 [=12= 的包装器 clojure.core/format
].
您可以使用 <<
string interpolation macro from the core.incubator 项目。
要使用它,请将 [org.clojure/core.incubator "0.1.4"]
添加为 project.clj
文件中的依赖项。 (注意:查看 core.incubator 的 GitHub page 以获得最新的安装说明。)
使用示例:
(ns example
(:require [clojure.core.strint :refer [<<]]))
(def my-name "XYZ")
(<< "My name is ~{my-name}.")
; Returns: "My name is XYZ."
(let [x 3
y 4]
(<< "~{x} plus ~{y} equals ~(+ x y)."))
; Returns: "3 plus 4 equals 7."
注意花括号 ~{}
和圆括号 ~()
.
的区别
虽然不是图书馆,但在 Clojure, the Essential Reference 书中找到了这个例子。
replace
could be used to implement a simple textual substitution
system. An input string contains special placeholders that the system
can identify and replace from a list of known substitutions:
(def text "You provided the following: user {usr} password {pwd}")
(def sub {"{usr}" "'rb075'" "{pwd}" "'xfrDDjsk'"})
(transduce
(comp
(replace sub)
(interpose " "))
str
(clojure.string/split text #"\s"))
;; "You provided the following: user 'rb075' password 'xfrDDjsk'"
我正在寻找一个(最好是小的)Clojure 库,它在 clojars 中可用,它允许我替换字符串中的简单模板,例如:
"Hello my name is ${name}"
其中 ${name}
应由模板引擎替换。在 Java 中,我通常使用完美的 JMTE。我知道我也可以从 Clojure 中使用它,但我想知道是否有比 Clojure 更多的东西 friendly/idiomatic.
我找到了 this。
也许这就是您要找的。
有很多模板库。一些通用的是:
注意:如果您只需要一些巧妙的格式化,您可以使用带有 cl-format
函数的标准库 clojure.pprint 和 [=12= 的包装器 clojure.core/format
].
您可以使用 <<
string interpolation macro from the core.incubator 项目。
要使用它,请将 [org.clojure/core.incubator "0.1.4"]
添加为 project.clj
文件中的依赖项。 (注意:查看 core.incubator 的 GitHub page 以获得最新的安装说明。)
使用示例:
(ns example
(:require [clojure.core.strint :refer [<<]]))
(def my-name "XYZ")
(<< "My name is ~{my-name}.")
; Returns: "My name is XYZ."
(let [x 3
y 4]
(<< "~{x} plus ~{y} equals ~(+ x y)."))
; Returns: "3 plus 4 equals 7."
注意花括号 ~{}
和圆括号 ~()
.
虽然不是图书馆,但在 Clojure, the Essential Reference 书中找到了这个例子。
replace
could be used to implement a simple textual substitution system. An input string contains special placeholders that the system can identify and replace from a list of known substitutions:
(def text "You provided the following: user {usr} password {pwd}")
(def sub {"{usr}" "'rb075'" "{pwd}" "'xfrDDjsk'"})
(transduce
(comp
(replace sub)
(interpose " "))
str
(clojure.string/split text #"\s"))
;; "You provided the following: user 'rb075' password 'xfrDDjsk'"