lisp - 使用 cl-who、parenscript 和 hunchentoot 生成内联 javascript

标签 lisp common-lisp hunchentoot cl-who parenscript

我正在尝试生成内联 javascript,但我必须使用 cl-who 将 parenscript 代码放入 (:script)(str) 标记内。 psps*ps-inlineps-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))

最佳答案

宏在此用例中很好。 技巧在于宏按特定顺序展开。说 你定义了 js宏:当宏展开遇到 with-html-output ,对宏的内部调用 (js (alert "Ho Ho Ho"))看起来像一个函数调用,并在生成的文件中按原样保留 代码。如果您jsthen 扩展为 (:script ...) ,那么系统会提示:script是一个未知函数(假设你 实际上并没有命名这样的函数)。你应该发出一个 附上(who:htm ...)使用表达式来解释代码 CL-WHO 的代码步行者。

(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>

关于lisp - 使用 cl-who、parenscript 和 hunchentoot 生成内联 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916865/

相关文章:

prototype - Lisp 和 Scheme 存在哪些 POOP 框架

binding - 如何刷新、重制 lambda 上的词法绑定(bind)?

arrays - Lisp 格式过程应用于数组

common-lisp - 在多值绑定(bind)中使用值形式的变量

debugging - 从 REPL 访问 Hunchentoot 请求对象以进行调试

javascript - 是否可以在 Hunchentoot 中实现服务器端事件?

lisp - 从逻辑列表中选择。口齿不清

lisp - 方案: "expects 1 argument, given 4"奇怪的行为

lisp - Common Lisp 超规范 : unbound symbol handling in conforming implementations

common-lisp - 在 hunchentoot 中有没有办法在路径之前获取 url 的一部分