【问题标题】:Generating inline javascript with cl-who, parenscript and hunchentoot使用 cl-who、parenscript 和 hunchentoot 生成内联 javascript
【发布时间】:2018-06-03 15:40:19
【问题描述】:

我正在尝试生成内联 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))

【问题讨论】:

    标签: lisp common-lisp hunchentoot cl-who parenscript


    【解决方案1】:

    宏在这个用例中很好。 诀窍是宏以特定顺序展开。说 你定义了一个js 宏:当遇到宏扩展时 with-html-output,对宏 (js (alert "Ho Ho Ho")) 的内部调用看起来像一个函数调用,并在生成的 代码。如果你的js然后扩展成(: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>
    

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2011-04-17
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      相关资源
      最近更新 更多