我正在尝试生成内联javascript,但我必须使用cl将parenscript代码放入(:script)和(str)标记中。ps、ps*、ps-inline和ps-inline*似乎对生成的js没有多大影响。
是通常编写宏以避免代码重复的方法,还是有更好的方法?
这是我的节目:
(in-package #:ps-test)
(defmacro standard-page ((&key title) &body body)
`(with-html-output-to-string (*standard-output* nil :prologue t :indent t)
(:html
:lang "en"
(:head
(:meta :http-equiv "Content-Type"
:content "text/html;charset=utf-8")
(:title ,title)
(:link :type "text/css"
:rel "stylesheet"
:href "/style.css"))
(:body
,@body))))
(defun main ()
(with-html-output (*standard-output* nil :indent t :prologue nil)
(standard-page (:title "Parenscript test")
(:div (str "Hello worldzors"))
(:script :type "text/javascript"
(str (ps (alert "Hello world as well")))))))
(define-easy-handler (docroot :uri "/") ()
(main))
(defun start-ps-test ()
(setf (html-mode) :html5)
(setf *js-string-delimiter* #\")
(start (make-instance 'hunchentoot:easy-acceptor :port 8080)))
(defun stop-ps-test ()
(stop *server*))
(defvar *server* (start-ps-test))发布于 2017-12-21 14:16:16
宏在这个用例中很好。诀窍是宏按特定顺序展开。假设您定义了一个js宏:当宏扩展遇到with-html-output时,对宏(js (alert "Ho Ho Ho"))的内部调用看起来就像一个函数调用,并保留在生成的代码中。如果您的js宏随后扩展为(:script ...),那么系统会抱怨:script是一个未知的函数(假设您实际上没有这样命名一个函数)。您应该发出一个封闭的(who:htm ...)表达式来使用CL的代码遍历器来解释代码。
(defmacro js (code)
`(who:htm
(:script :type "text/javascript" (who:str (ps:ps ,code)))))这只适用于一个封闭的with-html-output的上下文。
对于内联Javascript,您不希望在它周围有一个<script>标记,您通常可以简单地使用ps-inline
(who:with-html-output (*standard-output*)
(:a :href (ps:ps-inline (void 0))
"A link where the usual HREF behavior is canceled."))
;; prints:
;;
;; <a href='javascript:void(0)'>A link where the usual HREF behavior is canceled.</a>但是,如果您经常做同样的事情,可以随意使用宏:
(defmacro link (&body body)
`(who:htm (:a :href #.(ps:ps-inline (void 0)) ,@body)))
(who:with-html-output (*standard-output*) (link "Link"))
;; prints:
;;
;; <a href='javascript:void(0)'>Link</a>https://stackoverflow.com/questions/47916865
复制相似问题